What I’m trying to do is write a method that will return all of this model’s outing_locations, to which it has a 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 to get this block in particular to work.
There’s another model called OutingInvite, which contains the id of a particular Outing. I need to use that to grab the proper Outing and then pull said Outing’s associated outing locations.
Here’s a rough sample:
<%@outing_invites.each do |invite|%>
...
<% @party = Outing.where(:id => invite.outing_id) %>
<% @party.outing_locations.each do |location| %>
And then have it output each location.
However, it’s saying the method ‘outing_locations’ does not exist…
You can see a model’s associated models by typing
model_instance.associated_model_name.So in your example, anoutinghas_manyouting_locations. After you have an instance of anouting, say by using@o = Outing.find(1), you can then useo.outing_locationsto see theouting_locationsassociated with that specificouting.See this example from the Ruby on Rails Guide.
EDIT
The reasons you’re getting the
method 'outing_locations' does not existerror is becauseOuting.where(:id => invite.outing_id)returns an array, and there is noouting_locationsmethod for arrays. You’ll need to either get the specific instance (like withOuting.find(invite.outing_id) or use a specific index in that array. I recommend usingOuting.find(invite.outing_id)since (I’m assuming) each of your Outing’s has a unique id.