在轨道上的ruby中查找关联中的所有内容

Has*_*mad 5 activerecord join ruby-on-rails include

在这里,我已经有了之间的1对多的关系ProductsUsers:

class Property < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :property
end
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得不属于任何用户的所有属性?

小智 6

要获取没有用户的所有属性,请尝试以下操作:

Property.includes(:users).where(users: { property_id: nil })
Run Code Online (Sandbox Code Playgroud)


Uda*_*das 0

使用此代码:

@users= User.includes(:properties).where(properties: { property_id: nil })
Run Code Online (Sandbox Code Playgroud)