Mongoid single object related to multiple fields
Is it possible to relate a single object as multiple fields? Something like this?
Ad Model
class Ad
include Mongoid::Document
field :name
referenced_in :ad_types, :as => :web_spec
referenced_in :ad_types, :as => :print_spec
end
开发者_运维知识库
AdType Model
class AdType
include Mongoid::Document
field :shape
field :size
field :medium
references_many :ads
end
Then reference each reference as a separate field in a form like this.
<%= f.input :web_spec, :collection => AdType.where(:medium => "Web"), :label_method => :shape, :label => "Web" %>
<%= f.input :print_spec, :collection => AdType.where(:medium => "Print"), :label_method => :shape, :label => "Print" %>
I've given something like this with no luck. I'm probably going about it the wrong way or this feature just doesn't exist yet. Any suggestions would be great appeciated.
A few questions. Is there a reason why AdType is a document unto itself? Unless you're going to have a large number of types, it might make more sense for it to be an embedded document. Secondly, what might be cleaner is having a single association (regardless if it's referenced or embedded) and two scopes to your Ad model. Using your example, I'd have something like this:
class Ad
include Mongoid::Document
field :name
embeds_one :ad_type
scope :web ...
scope :print ...
end
class AdType
include Mongoid::Document
field :shape
field :size
field :medium
embedded_in :ad, :inverse_of => :ad_type
end
精彩评论