我在轨道4中,我正在尝试执行:
User.properties.where(:property_id => 2).first
这会产生一个sql错误,我理解并知道为什么我不能这样做。但我只是想知道使用Rails 4中的:has_many关联通过外键查找的正确方法。
与此类似(显然有效):
Property.where(:id => 1).first
答案 0 :(得分:1)
试试这个:
User.joins(:properties).where('properties.id' => 2).first
如果您想加载属性,请使用includes
代替joins
。
答案 1 :(得分:0)
问题是where
是properties
表格,我猜测它没有property_id
列。
你可以这样做:
user.properties.where(id: 2).first
更好的方法可能就是这样:
user.properties.find(2)