Reputation: 71
I have 3 tables Ledgers, Accounts, Users and organisation
I am trying to get accounts using ledger Id for each specific user.
Table Ledgers contains - LedgerID, Organisation ID
Table Accounts contains - AccountID, AccountName, LedgerID
Table Users contains - UserID, name
Table Organisation contains - OrganisationId, UserID, organisation name
Heres my models.
class Accounts < ActiveRecord::Base
belongs_to :ledger
end
class Ledger < ActiveRecord::Base
has_many :accounts
belongs_to :organisation
end
class User < ActiveRecord::Base
has_many :organisations
end
Here is what i have tried.
def show
if authenticated_user
@Usersorganisations = @authenticated_user.organisations
# This gets the user's organisations
@ledger_id = Ledger.where("organisation_id = ?", @Usersorganisations.pluck(:id))
render json: @ledger_id.as_json
end
But trying this gives me PG::DatatypeMismatch: ERROR:
Upvotes: 0
Views: 45
Reputation: 2616
The issue with your code above is that @Usersorganisations.pluck(:id)
returns an array, and you're trying to do an sql comparison =
instead of using the IN
operator.
You can overcome this in the code you have above by simply changing that line to:
@ledger_id = Ledger.where(organisation_id: @Usersorganisations.pluck(:id))
A better approach might be to use the rails has many through associations where you define the association in User such as:
class User < ActiveRecord::Base
has_many :organisations
has_many :ledgers, through: :organisations
end
after which, you can simply do the following in your controller:
@ledgers = @authenticated_user.ledgers
Upvotes: 2