Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 just 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.

like image 980
Pedro Cori Avatar asked Dec 17 '22 08:12

Pedro Cori


2 Answers

I'd do:

campaign.points.map(&:locale)
like image 85
apneadiving Avatar answered May 08 '23 08:05

apneadiving


campaign.points.map {|p| p.locale}

should do the trick.

like image 45
lucapette Avatar answered May 08 '23 08:05

lucapette