如何过滤 model1 has_many model2 has_one model3(多态)?
how filter model1 has_many model2 has_one model3 (polymorphic)?
我有型号用户,然后
has_many :estates, dependent: :destroy
具有多态关联的模型Estate
has_one :location, as: :locatable, dependent: :destroy
在位置迁移中,我有
class CreateLocations < ActiveRecord::Migration
def change
create_table :locations do |t|
t.string :address
t.decimal :lat, {:precision=>10, :scale=>6}
t.decimal :lng, {:precision=>10, :scale=>6}
t.references :locatable, polymorphic: true, index: true
我如何从 Location.address 中过滤或找到 用户 ?
我试过了
User.where(estates: { location: { address: "London" } })
出现这个错误
SQLite3::SQLException: no such column: estates.locatable_id:
SELECT "users".* FROM "users" WHERE "estates"."locatable_id" = '-
--
:address: !ruby/object:Arel::Nodes::BindParam {}'
可能是
User.includes(:estates).where
提前致谢!
我认为您正在寻找的是使用联接来查找用户。
User.joins(estates: :location).where(locations: {address: "London"})
这会告诉您的 sql 调用将用户与庄园和庄园与位置相匹配,并且 select 仅匹配位置为 "London" 的用户。
我有型号用户,然后
has_many :estates, dependent: :destroy
具有多态关联的模型Estate
has_one :location, as: :locatable, dependent: :destroy
在位置迁移中,我有
class CreateLocations < ActiveRecord::Migration
def change
create_table :locations do |t|
t.string :address
t.decimal :lat, {:precision=>10, :scale=>6}
t.decimal :lng, {:precision=>10, :scale=>6}
t.references :locatable, polymorphic: true, index: true
我如何从 Location.address 中过滤或找到 用户 ? 我试过了
User.where(estates: { location: { address: "London" } })
出现这个错误
SQLite3::SQLException: no such column: estates.locatable_id:
SELECT "users".* FROM "users" WHERE "estates"."locatable_id" = '-
--
:address: !ruby/object:Arel::Nodes::BindParam {}'
可能是
User.includes(:estates).where
提前致谢!
我认为您正在寻找的是使用联接来查找用户。
User.joins(estates: :location).where(locations: {address: "London"})
这会告诉您的 sql 调用将用户与庄园和庄园与位置相匹配,并且 select 仅匹配位置为 "London" 的用户。