我正在Rails 4中创建一个公交时间表应用程序,并且我有一个时间表类,每个记录都有一个公交站,属于一个公交车服务外键。在Rails中自加入查询。未定义的方法错误
我想显示每个巴士服务提供的原点和目的地点。我在时间表类(bus_service)上进行自加入,以便将属于特定总线服务的起点和终点站的时间表条目链接起来。
型号。 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
控制器:timetable_controller.rb
@timetables = Timetable.joined(params[:from_stop_id], params[:to_stop_id])
查看: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 %>
生成的SQL看起来不错:
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')
但我得到一个未定义的方法'timetable_sister'错误的视图文件。 时间表中的NoMethodError#索引
我应该如何在视图中呼叫姐妹电台名称?或者我正在做其他事情。
感谢
您对“timetable_sisters”有'to many'关系。因此你不能调用.timetable_sister。相反,你需要遍历结果,例如'timetable.timetable_sisters.each' –
这就是伟大的davidsatch。有用。 :)但逻辑上它给了两个姐姐时间表停止结果。如何将结果限制在列中未列出的结果之前? – Enrique