Ruby on Rails 3: How to access an attribute of each record in a has_many query
I wasn't sure how to phrase it in the title, but what I'm trying to do the following. I have 2 models that have the following relationships:
class Campaign < ActiveRecord::Base
has_many :points
end
class Point < ActiveRecord::Base
belongs_to :campaign
end
Now, the Point model has a "locale" attribute and I want to be able to put all the "locales" of every point of a specific campaign into an array, or collection, or whatever without having to do something like
locales = Array.new
campaign.points.each do |p|
locales << p.locale
end
I was thinking of something along the lines of campaign.points.locales
. Is there some nice Rails way of doing this query, or do I ju开发者_开发技巧st have to iterate over the collection?
Thanks for any help.
EDIT: Also because the relationship is actually a "has_many through" relationship, this method doesn't work, as I get many repeated locales if I try to iterate in that simple way. It sounds like it should be some type of join, but I'm not sure.
I'd do:
campaign.points.map(&:locale)
campaign.points.map {|p| p.locale}
should do the trick.
You could do what those guys said. Put a .uniq
at the end of them and end up with the correct solution, or;
let me lead you astray with ActiveRecord fun (and possibly failure, since I can't test to see if it works here). But you'll be able to run campaign.points.locales
just like you wanted.
class Campaign < ActiveRecord::Base
has_many :points do
def locales
select('DISTINCT(locale)').map(&:locale)
end
end
end
精彩评论