Reputation: 351
I have three models. They are like below
class User < ApplicationRecord
has_one :shop
has_one :address
end
class Shop < ApplicationRecord
belongs_to :user
end
class Address < ApplicationRecord
belongs_to :user
end
Address model has state_id column. Now I want to get all shops which shop's owner address.state_id
is 123456.
Upvotes: 1
Views: 2274
Reputation: 6476
You can describe relation of Shop
and Address
via User
. Like this:
# models/shop.rb
class Shop < ApplicationRecord
belongs_to :user
has_one :address, through: :user
end
Then you can issue a simple call:
Shop.includes(:address).where(addresses: { state_id: 123456 })
Upvotes: 1
Reputation: 52357
Shop.joins(user: :address).where(addresses: { state_id: 123456 })
Upvotes: 2