I have a has_many :through association, and I am iterating over the children to put together some info. But I would also like to get some information out of the join table in the loop. Here is the method with blaring comments around the section that needs help. Am I able to get that membership number from the join table in a simple manner like this?
class Customer < ActiveRecord::Base
has_many :customer_memberships
has_many :membership_programs, :through => :customer_memberships
def membership_info_to_json
info ={"benefits" => [], "omitted_stuff" => {}}
self.membership_programs.each do |membership|
##################################################################
#THIS INFO IS IN THE JOIN TABLE ##################################
info["membership_numbers"] << customer_membership.membership_number
##################################################################
#Omitted: the rest of the loop deals with membership.
end
info.to_json
end
Something about your attempt is confusing me. I'm not exactly sure what it is but unless I'm mistaken, a membership_program is going to also have many customer_memberships. If that's the case then you'll have to collect each for that membership.
def membership_info_to_json
info ={"membership_numbers"=>[], "benefits" => [], "omitted_stuff" => {}}
self.membership_programs.each do |membership|
info["membership_numbers"] << membership.customer_memberships.collect{|cm| cm.membership_number}
end
info["membership_numbers"].flatten!
info.to_json
end
I hope that helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.