I am creating a bus timetable app in Rails 4 and I have a timetable Class on which each record has a bus stop and belongs to a bus service foreign key.
I want to display the origin and destination stops served by each bus service. I do a self join on the Timetable class (bus_service) to link the timetable entries for origin and destination stops belonging both to a specific bus service.
Model. timetable.rb
has_many :timetable_sisters, class_name: "Timetable", primary_key: "bus_service_id", foreign_key: "bus_service_id"
belongs_to :timetable_sister_b, class_name: "Timetable", foreign_key: "bus_service_id"
belongs_to :bus_stop
belongs_to :bus_service
def self.joined(from_stop_id, to_stop_id)
joins(:timetable_sisters).
where("timetables.bus_stop_id = ? AND timetable_sisters_timetables.bus_stop_id = ?", from_stop_id, to_stop_id)
end
Controller:timetable_controller.rb
@timetables = Timetable.joined(params[:from_stop_id], params[:to_stop_id])
View: index.html.erb
<% @timetables.each do |timetable| %>
<tr>
<td><%= timetable.bus_service_id %></td>
<td><%= timetable.bus_stop.name %></td>
<td><%= timetable.timetable_sister.bus_stop.name %></td>
<td><%= timetable.departure_time %></td>
</td></tr>
<% end %>
The generated SQL looks fine:
SELECT "timetables".*
FROM "timetables"
INNER JOIN "timetable_sisters" "timetable_sisters_timetables"
ON "timetable_sisters_timetables"."bus_service_id" = "timetables"."bus_service_id"
WHERE (timetables.bus_stop_id = '25'
AND timetable_sisters_timetables.bus_stop_id = '27')
But I get a undefined method `timetable_sister' error on the view file. NoMethodError in Timetables#index
How should I call for the sister station name in the view? Or I am doing something else wrong.
Thanks
timetable_sisters. Therefore you can't call .timetable_sister. Instead, you will need to iterate through the results, for example,timetable.timetable_sisters.each