0

Here is what 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.

vonconrad
  • 25,227
  • 7
  • 68
  • 69
AMIT
  • 539
  • 1
  • 4
  • 13

3 Answers3

0

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

elithrar
  • 23,364
  • 10
  • 85
  • 104
  • I appreciate your answer, but I'm not quite sure i understood :) An announcement cannot stretch across multiple clients. I already have this thing working but that involves a lot of ruby code and multiple db hits which i'd like to eliminate. I was looking for something in ActiveRecord. But i guess, there is no direct way of doing this, w/o creating a new relation. – AMIT Dec 29 '10 at 16:10
0

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

elithrar
  • 23,364
  • 10
  • 85
  • 104
0

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
dombesz
  • 7,890
  • 5
  • 38
  • 47