Rails中的自联接查询。未定义的方法错误

时间:2015-10-20 05:12:34

标签: ruby-on-rails ruby-on-rails-4 self-join

我正在Rails 4中创建一个公交时刻表应用程序,我有一个时间表类,每个记录都有一个公共汽车站,属于公共汽车服务外键。

我想显示每个巴士服务所服务的起点和终点站。我在Timetable类(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&#39; 错误。 时间表#index

中的NoMethodError

我应该如何在视图中呼叫姐妹电台名称?或者我做错了。

由于

2 个答案:

答案 0 :(得分:1)

<% @timetables.each do |timetable| %>
<tr>
<td><%= timetable.bus_service_id %></td>
<td><%= timetable.bus_stop.name %></td>
<td><% timetable.timetable_sisters.each do |t_sis| %>
    <%= t_sis.bus_stop.name %>, 
<% end %></td>
<td><%= timetable.departure_time %></td>
</td></tr>
<% end %>

答案 1 :(得分:0)

为了我的理智,

#app/models/timetable.rb
class Timetable < ActiveRecord::Base
   #columns id | service_id | bus_stop_id | arrival_time | created_at | updated_at
   belongs_to :bus_stop
   belongs_to :service
end

#app/models/service.rb
class Service < ActiveRecord::Base
   #columns id | name | number | etc | created_at | updated_at
   has_many :timetables
   has_many :bus_stops, through: :timetables
end

#app/models/bus_stop.rb
class BusStop < ActiveRecord::Base
   #column id | name | geox | geoy | created_at | updated_at
   has_many :timetables
   has_many :services, through: :timetables
end
  

我想显示每个巴士服务所服务的起点和终点站

然后你就能做到:

@services = Service.all
@services.each do |service|
   # service.number -> "56"
   service.bus_stops.each do |stop|
      stop.name #-> "
   end
end

如果您想绘制特定路线,您可以执行以下操作:

@service = Service.find "1"
@services = Timetable.where service: @service

@services.each do |route|
   route.bus_stops.each do |stop|
      stop.name
      stop.geox
      stop.geoy
   end
end

这仍然是粗略的,但它应该有用。

我没有包含“目的地”/“原点”巴士站,因为它们未在模型中定义。我想要包含一个Route模型,但我无法通过示例数据使其工作。

希望这有帮助!