views:

1733

answers:

2

Say if @news_writers is an array of records. I then want to use @news_writers to find all news items that are written by all the news writers contained in @news_writers.

So I want something like this (but this is syntactically incorrect):

@news = News.find_all_by_role_id(@news_writers.id)

Note that

class Role < ActiveRecord::Base
  has_many :news
end

and 

class News < ActiveRecord::Base
  belongs_to :role
end
+1  A: 

I'm not sure if I understand you - @news_writers is a collection of Role models? If that assumption is correct, your association appears to be backwards - if these represent authors of news items, shouldn't News belong_to Role (being the author)?

At any rate, I would assume the most direct approach would be to use an iterator over @news_writers, calling on the association for each news_writer (like news_writer.news) in turn and pushing it into a separate variable.

Edit: Daniel Lucraft's suggestion is a much more elegant solution than the above.

ennen
You're right, I fixed that association.
alamodey
+2  A: 

Like ennen, I'm unsure what relationships your models are supposed to have. But in general, you can find all models with a column value from a given set like this:

  News.all(:conditions => {:role_id => @news_writers.map(&:id)})

This will create a SQL query with a where condition like:

  WHERE role_id IN (1, 10, 13, ...)

where the integers are the ids of the @news_writers.

Daniel Lucraft