How do you write a Rails model method to return a list of its associations? -
what i'm trying write method return of model's outing_locations, has has_many relationship.
class outing < activerecord::base attr_accessible :description, :end_time, :start_time, :title, :user_id belongs_to :user has_many :outing_locations has_many :outing_guests has_one :time_range, :foreign_key => "element_id", :conditions => { :element_type => "outing" } validates :title, :presence => true validates :start_time, :presence => true # regex validates :end_time, :presence => true # regex def host_name return user.find(self.user_id).full_name end end i'm trying block in particular work.
there's model called outinginvite, contains id of particular outing. need use grab proper outing , pull said outing's associated outing locations.
here's rough sample:
<%@outing_invites.each |invite|%> ... <% @party = outing.where(:id => invite.outing_id) %> <% @party.outing_locations.each |location| %> and have output each location.
however, it's saying method 'outing_locations' not exist...
you can see model's associated models typing model_instance.associated_model_name. in example, outing has_many outing_locations. after have instance of outing, using @o = outing.find(1), can use o.outing_locations see outing_locations associated specific outing.
see this example ruby on rails guide.
edit
the reasons you're getting method 'outing_locations' not exist error because outing.where(:id => invite.outing_id) returns array, , there no outing_locations method arrays. you'll need either specific instance (like outing.find(invite.outing_id) or use specific index in array. recommend using outing.find(invite.outing_id) since (i'm assuming) each of outing's has unique id.
Comments
Post a Comment