I have the below Model structure
class Transaction
belongs_to :company
belongs_to :user
end
class Company
belongs_to :address
end
class User
belongs_to :address
end
classAddress
has_many :companies
has_many :users
end
I want to query all transactions and get both company address and user address
Transaction.joins([company: :address], [user: :address])
.select('company.addresses.line_1 as company_add_line1',
'user.addresses.line_1 as user_add_line1')
For the syntax ‘company.addresses.line_1’, I am getting the below error
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'company.addresses.line_1' in 'field list'
How t achieve this?
2
Answers
I note that your User and Company each should
have_many :transactions
Your syntax fails b/c you have ActiveRecord-like syntax (e.g.
companies.addresses.line1
inside a SQL snippet)You need something like this…
You have not mentioned has_many :transactions in the company and users model.
Cross-check the field with your schema fields this will work.