Md. Sahidul Islam
Md. Sahidul Islam

Reputation: 351

How to query on multiple tables in rails?

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

Answers (2)

Krule
Krule

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

Andrey Deineko
Andrey Deineko

Reputation: 52357

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

Upvotes: 2

Related Questions