Reputation: 3
I am trying to show relations between two tables but i get
undefined method `guiders' for # <ActiveRecord::Relation::ActiveRecord_Relation_Trip:0x3865e78>
--controller code for showguiders--
class ShowguidersController < ApplicationController
def guidersout
r = Trip.all
@guiders_out = r.guiders
end
end
model for guider
class Guider < ActiveRecord::Base
belongs_to :trip
end
model for trip
class Trip < ActiveRecord::Base
has_many :guides
end
view
this is what my professor had on his
<center><h1> Here are our Guides </h1>
<br /><br /><br /><br />
<table width = 60% border =1>
<tr><th>Guide # </th><th> Name </th> <th> Phone </th> </tr>
<% @guiders_out.each do |m| %>
<tr><td> <%= m.id %> </tr> </td> <tr><td> <%= m.name %> </tr> </td> <tr><td> <%= m.phone %> </tr> </td>
<% end %>
</table></center>
<br /><br /><br /><br />
Upvotes: 0
Views: 844
Reputation: 5734
You need all the guiders who are associated with all the trips. Have a try with this code
def guidersout
@guiders_out = Guider.joins(:trip).all
end
I found you have to modify in your model as well.
class Trip < ActiveRecord::Base
has_many :guides, class_name: 'Guider', foreign_key: 'trip_id'
end
After modifying your model, you can try with the following code in your controller.
def guidersout
@guiders_out = Trip.all.map{|t| t.guides}.flatten
end
In your view, Please change the table.
<table width = 60% border =1>
<tr>
<th>Guide # </th>
<th> Name </th>
<th> Phone </th>
</tr>
<% @guiders_out.each do |m| %>
<tr>
<td> <%= m.id %> </td>
<td> <%= m.name %> </td>
<td> <%= m.phone %></td>
</tr>
<% end %>
Upvotes: 1
Reputation: 7434
You are calling a method on a collection of ActiveRecord models (i.e. a Relation
).
To return a collection of each Guider
of every Trip
, you'll first need to model your associations properly. Try this
class Guider < ActiveRecord::Base
belongs_to :trip
end
class Trip < ActiveRecord::Base
# NOTE: you must match your association name with its associated class
has_many :guiders
end
Now you can aggregate the collection in the controller like so
class ShowguidersController < ApplicationController
def guidersout
@guiders_out = Trip.all.collect(&:guiders).flatten
end
end
Upvotes: 1
Reputation: 160963
One Trip
has many guiders
, but not the collection.
If you want to get all of it, use:
@guiders_out = r.map(&:guiders)
Upvotes: 1