Here is wh开发者_如何学编程at i have.
client has_many branches
branch has_many projects
project has_and_belongs_to_many announcements
Is there an easier way to find the announcements given a client?
I need a unique collection of announcements.
If a Client can have multiple Announcements, but an Announcement can only belong to one Client, then use:
Client:
has_many :announcements
Announcement:
belongs_to :client
This keeps it within ActiveRecord. You can find Announcements for a given Client with some quick method calls. Scroll down to "Association Join Models" for examples: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
Why not create a join table to handle the many-to-many relationship between your Client and Announcement models? Something like:
Client:
has_many :announcements, :through => :client_announcements
Announcement:
has_many :clients, :through => :client_announcements
ClientAnnouncements:
belongs_to :client
belongs_to :project
Then you can set an object to find the announcements attached to a particular client ID, or vice-versa.
PS: Answer may not be exhaustive, I'm not a native Rails dev — check the API docs for examples on what I've touched on: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
You can create a new relation using the uniq symbol on habtm
has_and_belongs_to_many :uniq_announcements, :source=>:announcements, :uniq=>true
or just simply call uniq!
project.announcements.uniq
精彩评论