2016-11-04 61 views
0

我有三種模式。它們如下所示如何查詢rails中的多個表?

class User < ApplicationRecord 
    has_one :shop 
    has_one :address 
end 

class Shop < ApplicationRecord 
    belongs_to :user  
end 

class Address < ApplicationRecord 
    belongs_to :user  
end 

地址模型有state_id列。現在,我想所有的商店,其店的老闆address.state_id爲123456

回答

1
Shop.joins(user: :address).where(addresses: { state_id: 123456 }) 
1

您可以通過User描述ShopAddress關係。就像這樣:

# models/shop.rb 
class Shop < ApplicationRecord 
    belongs_to :user 
    has_one :address, through: :user 
end 

然後你就可以發出簡單的呼叫:

Shop.includes(:address).where(addresses: { state_id: 123456 })