belongs_to :listable, polymorphic: true
belongs_to :car, -> { where(listings: {listable_type: 'Car'}) }, foreign_key: 'listable_id'
def car
return unless listable_type == "Car"
super
end
listing = Listing.first
listing.car
ActiveRecord :: StatementInvalid(PG :: UndefinedTable:错误:缺少 表“列表”的FROM子句条目)第1行:.... * FROM“ cars” WHERE“ cars”。“ id” = $ 1 AND“ listings” ... ^:选择“ cars”。*从“ cars”到“ cars”。“ id” = $ 1并且 “ listings”。“ listable_type” = $ 2 LIMIT $ 3
我也尝试过:
belongs_to :car, -> { joins(:listings).where(listings: {listable_type: 'Car'}) }, foreign_key: 'listable_id'
然后我得到了
ActiveRecord :: ConfigurationError(无法加入“汽车”进行关联 命名为“列表”;也许您拼错了?)
是什么导致此错误?