Models -> has_many -> Twice
So I have a somewhat confusing relationship here, between a Note, Group, and User. And I ended up with has_many twice in my model. But I'm开发者_如何转开发 currently focused on the Note & Group relationship.
Background: A Group can have a note. A User can also have a note. Which is why my Note is polymorphic. However, I also created a join model called a Tag, so that a Note can belong to multiple groups. In my code though, I ended up with multiple 'has_many :notes'. See all of my code below. What would be the proper way to do something like this?
Thanks in advance!
note.rb
belongs_to :notable, :polymorphic => true
has_many :tags
has_many :groups, :through => :tags
user.rb
has_many :notes, :as => :notable
group.rb
has_many :notes, :as => :notable
has_many :tags
has_many :notes, :through => :tags
tag.rb
belongs_to :note
belongs_to :group
You just need to give it a different name.
class Group
has_many :notes, :as => :notable
has_many :tags
has_many :tagged_notes, :class_name => 'Note', :through => :tags
end
If you only want a single note for the :as => :notable
part (this wasn't very clear in your question), you could just do this:
class Group
has_one :note, :as => :notable
has_many :tags
has_many :notes, :through => :tags
end
The names just have to be different. Although with note
vs. notes
it might not be very clear what the distinction is in other parts of your code.
精彩评论