Mongoid - One way references - mongoid

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.

Related

Mongoid: Is it possible to treat a reference as if it was embedded?

class Part
include Mongoid::Document
belongs_to :type
# data
end
class Type
include Mongoid::Document
has_many :parts
field :name
# data
end
Let's say I have a design like the above. I need to have it in such a way that Type exists independently of any Part, both because this is the logical structure and because Types can change and I want to be able to do that centrally. But when I find a Part, I'd like to have it's associated Type embedded in the document returned. I want to do this because in almost any case I need to use the data in a Part, I need the data from its associated Type. When I get the JSON on my client side, it only containes type_id but no Type data. Is there any automatic what to include the data from Type in Part's JSON while retaining the benefits of references?
In the comments, mu answered that one can just override the as_json method of the model.
My implementation is as follows:
class Part
include Mongoid::Document
belongs_to :type
def as_json options = {}
if (options.has_key? :include and not options[:include].has_key? :type) or
not options.has_key? :include
options[:include] = :type
end
super.as_json(options)
end
end

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

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.

Finding Unassociated Records in Rails 3 with Mongoid?

My question is similar to this one, except I'm trying to do this in Mongoid.
I have two models:
class ImageUpload
include Mongoid::Document
referenced_in :post
end
class Post
include Mongoid::Document
references_many :image_uploads
end
How can I select the image uploads that are not associated with any post?
Have you tried following:
ImageUpload.where(:post_id => nil)

Mongoid relational Polymorphic Association

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

Resources