Mongoid relational Polymorphic Association - mongoid

Does anyone know how to do a polymorphic association in Mongoid that is of the relational favor but not the embedding one.
For instance this is my Assignment model:
class Assignment
include Mongoid::Document
include Mongoid::Timestamps
field :user
field :due_at, :type => Time
referenced_in :assignable, :inverse_of => :assignment
end
that can have a polymorphic relationship with multiple models:
class Project
include Mongoid::Document
include Mongoid::Timestamps
field :name, :type => String
references_many :assignments
end
This throws an error saying unknown constant Assignable. When I change the reference to embed, this all works as documented in Mongoid's documentation, but I need it to be reference.
Thanks!

Answering to an ancient post, but someone may find it useful.
Now there's also a polymorphic belongs_to:
class Action
include Mongoid::Document
include Mongoid::Timestamps::Created
field :action, type: Symbol
belongs_to :subject, :polymorphic => true
end
class User
include Mongoid::Document
include Mongoid::Timestamps
field :username, type: String
has_many :actions, :as => :subject
end
class Company
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
has_many :actions, :as => :subject
end

From Mongoid Google Group it looks like this is not supported. Here's the newest relevant post I found.
Anyway, this is not to hard to implement manually. Here's my polymorphic link called Subject.
Implementing inverse part of relation might be somewhat more complicated, especially because you will need same code across multiple classes.
class Notification
include Mongoid::Document
include Mongoid::Timestamps
field :type, :type => String
field :subject_type, :type => String
field :subject_id, :type => BSON::ObjectId
referenced_in :sender, :class_name => "User", :inverse_of => :sent_notifications
referenced_in :recipient, :class_name => "User", :inverse_of => :received_notifications
def subject
#subject ||= if subject_type && subject_id
subject_type.constantize.find(subject_id)
end
end
def subject=(subject)
self.subject_type = subject.class.name
self.subject_id = subject.id
end
end

Rails 4+
Here's how you would implement Polymorphic Associations in Mongoid for a Comment model that can belong to both a Post and Event model.
The Comment Model:
class Comment
include Mongoid::Document
belongs_to :commentable, polymorphic: true
# ...
end
Post / Event Models:
class Post
include Mongoid::Document
has_many :comments, as: :commentable
# ...
end
Using Concerns:
In Rails 4+, you can use the Concern pattern and create a new module called commentable in app/models/concerns:
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments, as: :commentable
end
end
and just include this module in your models:
class Post
include Mongoid::Document
include Commentable
# ...
end

Related

Multiple Polymorphic Model in Rails

Hey So i have a basic schema that I am implementing. Here are the basic Models
User - Public Free User of App
Organization - Subscribes to app, has employees
Employee - Belongs to an organization
Here are my polymorphic parts
Post - Can be made by employees or users
Image - Multiple can be attached to either posts or comments
Comment - Can be added to images or posts by either employees or users
Users and Employees are distinct.
The polymorphic image is done. Where i am having trouble is the comment part. How do i set this up so that the comment can be associated with either images or posts and can be posted by either employees or users. Here is what i have so far.
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Post < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Image < ActiveRecord::Base
has_many :comments, :as => :commentable
end
This sets it up so that the comment can belong to the post or image, how do i set it up so that the employee/user can have many comments as they add them? Or should i just split this up into EmployeeComments and UserComments.
It seems like i will need another table that will host the polymorphic ownership association.
You should just need to add another polymorphic belongs_to association to the Comment model which will represent the author of the comment.
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
belongs_to :authorable, :polymorphic => true
end
class User < ActiveRecord::Base
has_many :comments, :as => :authorable
end
class Employee < ActiveRecord::Base
has_many :comments, :as => :authorable
end

Mongoid unique model references

I'm using Mongoid 3. I have a simple class Tour and references multiple Itineraries. Is there a way that I can validate that for each tour, the itineraries' dates are unique, i.e. I can't have 2 itineraries of the same date for a single tour.
class Tour
has_many :itineraries
end
class Itinerary
field :date, :type => Date
validates :date, :presence => true
index({date: 1})
belongs_to :tour
end
I'm not sure how to set up the validation.
You can create custom validations :
class Tour
has_many :itineraries
validates :check_uniqueness_of_date # This line
# And this part
private
def check_uniqueness_of_date
# Check validation here
end
end
Another Stackoverflow Question
Rails Guides

Can't Save IDs from other tables into current table in database upon creation of an object Rails, Postgresql

I'm having problems getting multiple ids to save properly into my database.
I have a listing that has two parameters: a listing id and a price.
I've tried changing the controller to accept the current_user, and no luck there.
I've tried changing the model, and I've also tried manually creating a listing while giving it a user_id and book_id (checking that it is, indeed, giving the correct book and user ids). In the manual listing, I've also tried to make variable names without the # symbols, and though there are no errors, I'm still unable to store the values in the database
My listing model:
class Listing < ActiveRecord::Base
belongs_to :user
belongs_to :book
has_one :order
belongs_to :user, class_name: 'Listing'
attr_accessible :listing_id, :price
end
My user model:
class User < ActiveRecord::Base
has_many :books
has_many :listings
belongs_to :creator, class_name: 'User'
end
My book model:
class Book < ActiveRecord::Base
has_one :status
has_one :listing
belongs_to :user
attr_accessible :condition, :isbn, :location, :title, :weight, :comment, :description, :price
validates :isbn, :isbn_format => true
end
The create function in my listings controller
def create
#listing = Listing.new(params[:listing])
#listing.user_id = current_user_id
respond_to do |format|
if #listing.save
format.html { redirect_to #listing, notice: 'Listing was successfully created.' }
format.json { render json: #listing, status: :created, location: #listing }
else
format.html { render action: "new" }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
How I've tried to manually create the user_id and book_id columns:
<b><%= "Returned: "+doc.css("Ack").text %> </b> #returns if listing was a failure or success
<b><%= "Listing ID: "+doc.css("ItemID").text %></b> #returns the listing itemID
<% #book = Book.find_by_id(params[:book_id_num]) %><br /> #passed from a previous page
<% #user = User.find_by_id(current_user.id) %>
<%= #book.id %> #successfully displays the correct book id on the web page
<%= #user.id %> #successfully displays the id of the current_user
<% Listing.create(:listing_id => doc.css("ItemID").text, :price => price, :book_id => #book.id, :user_id => #user.id)%>
But doing it this way will only create a listing with a listing_id and a price.
I've been stuck for a while, and am unsure of how to proceed. I'm also fairly unfamiliar with how a database might function. Can anyone help me out?
I figured out the answer to my problem.
Using the rails console, it told me that it was unable to edit certain attributes in the creation of a listing.
I'm not sure if it's the rails way to do things, but if I allow the user_id and book_id to be accessible attributes, I am able to store the listing with the correct ids in the database. So my listing model looks as follows:
class Listing < ActiveRecord::Base
belongs_to :user
belongs_to :book
has_one :order
belongs_to :user, class_name: 'Listing'
attr_accessible :listing_id, :price, :user_id, :book_id
end
I can edit these values in the table appropriately when I create a listing.
Thanks to mu is too short for giving me the tip to check the creation of a listing in the rails console. I was not aware that it could be used in such a useful way.

rails and Mongoid, create Qualification system (Embed qualification into two Models)

i working on a little app to show some pictures.
Each picture can be "voted" or "qualified" in a scale of 1 to 5.
The qualification can be done for a logged user only one time.
I need to know the qualification of each image, and what image a user set the vote (and know the value of that vote), so i create this models:
class Voto
include Mongoid::Document
embedded_in :picture
embedded_in :user
field :value, :type => Integer
end
class Picture
include Mongoid::Document
embeds_many :votos
embeds_many :comments
belongs_to :user
...
...
end
class User
include Mongoid::Document
...
...
has_many :pictures
embeds_many :votos
end
But i don't know if this is correct. ¿Can i store the same model (in this case Voto) in two differents documents (Picture and User)?
Any idea how to achieve this?
You can do this by using the polymorphic flag
(see http://mongoid.org/en/mongoid/docs/relations.html#common Polymorphism)
class Voto
include Mongoid::Document
embedded_in :voteable, , polymorphic: true
field :value, :type => Integer
end
class Picture
include Mongoid::Document
embeds_many :votos, as: :voteable
embeds_many :comments
belongs_to :user
...
...
end
class User
include Mongoid::Document
...
...
has_many :pictures
embeds_many :votos, as: :voteable
end

Mongoid - One way references

Is it possible to do a one way reference in mongoid?
I would like to do something like:
class User
include Mongoid::Document
include Mongoid::Timestamps
has_many :blogs, :class_name => "Blog", :inverse_of => :editor
has_one :active_blog, :class_name => "Blog", :inverse_of => :active_users
end
and the blog model:
class Blog
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :editor, :class_name => "User", :inverse_of => :blogs
end
So, basically, I would like the User to store an object id referencing the blog that it is currently editing/posting to. I do not need the blog to know about the active users, only the other way around.
It seems like the canonical way to do this would be to use 'belongs_to' on the User, and 'has_many' on the Blog. This does work, but it isn't ideal because it doesn't really semantically express the relationship between the two models.
I am new to Mongoid, and have not been able to find a better answer. Is there a better way to set up this type of releationship?
Thanks a ton!
If you do not even want to create even the accessor active_user on blog side, you can have:
class User
belongs_to :active_blog, :class_name => "Blog", :inverse_of => nil
end
On the other hand has_many/has_one and belongs_to seems perfectly fine to me. It would not store user_ids in blog and blog doesn't need to know about active user unless you decide it should and start using the accessor from blog side.

Resources