【发布时间】:2019-01-21 09:56:56
【问题描述】:
我有两个相关的模型,Trip 和 Ride。一个行程可能有一个去程或回程。我的 ActiveRecord 模型如下所示:
class Route < ActiveRecord::Base
has_one :trip
end
class Trip < ActiveRecord::Base
belongs_to :going_route, class_name: "Route"
belongs_to :returning_route, class_name: "Route"
end
但是,当我想从路线访问行程时,这会给我带来一个问题:
Route.first.trip
这会引发 PostgreSQL 错误:
PG::UndefinedColumn: 错误:trips.route_id 列不存在
我如何告诉Route 班级他的行程属于going_route_id 或returning_route_id?或者也许还有其他方法?
P.S:我一直在寻找类似的问题,有很多,但没有一个完全像这个并解决了我的问题。如果您对如何使差异更清晰有任何提示,尤其是对于标题。 Here 是一些类似的问题
编辑:
我也尝试过使用 lambda,如 matthew's duplicate proposition:
class FavoriteRoute < ActiveRecord::Base
has_one :favorite_trip, -> (route) { where("going_route_id = :id OR returning_route_id = :id", id: route.id) }
end
这将引发相同的错误。如果我假设我应该使用find_by 而不是where,因为我只需要一个结果,我还有另一个我真的不明白的错误:
NoMethodError:#<0x00007f827b9d13e0>0x00007f827b9d13e0>
标签: ruby-on-rails ruby postgresql ruby-on-rails-4 activerecord