加入 Rails 中的两个或多个表?

Joining two or more tables in Rails?

我有 3 个表 Ledgers、Accounts、Users 和 organization

我正在尝试使用每个特定用户的分类帐 ID 获取帐户。

Table Ledgers contains - LedgerID, Organisation ID
Table Accounts contains  - AccountID, AccountName, LedgerID
Table Users contains - UserID, name
Table Organisation contains - OrganisationId, UserID, organisation name

这是我的模型。

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

这是我试过的。

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

但是尝试这个给了我 PG::DatatypeMismatch:错误:

你上面的代码的问题是 @Usersorganisations.pluck(:id) returns 一个数组,你试图做一个 sql 比较 = 而不是使用 IN 运算符.

您可以在上面的代码中解决这个问题,只需将该行更改为:

@ledger_id = Ledger.where(organisation_id: @Usersorganisations.pluck(:id))

更好的方法可能是使用 rails has many through associations 在用户中定义关联,例如:

class User < ActiveRecord::Base
  has_many :organisations
  has_many :ledgers, through: :organisations
end

之后,您只需在控制器中执行以下操作即可:

@ledgers = @authenticated_user.ledgers