简体   繁体   中英

Joining two or more tables in Rails?

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM