【问题标题】:Joining two or more tables in Rails?在 Rails 中加入两个或多个表?
【发布时间】:2017-05-20 06:54:15
【问题描述】:

我有 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: ERROR:

【问题讨论】:

  • 能否请您发布错误日志
  • 将代码示例发布为实际可运行代码并正确缩进是个好主意。您可能希望使用 schema.rb 的例外,因为如果您首先正确设置了表格而不是像问题文本中那样在 camelCase 中设置表格,那么这将消除问题。一般来说,代码总是比描述代码做什么的文本更好。

标签: mysql ruby-on-rails ruby-on-rails-3


【解决方案1】:

您上面的代码的问题是@Usersorganisations.pluck(:id) 返回一个数组,而您正在尝试对= 进行sql 比较,而不是使用IN 运算符。

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

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

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

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

之后,您可以在控制器中简单地执行以下操作:

@ledgers = @authenticated_user.ledgers

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 2014-07-22
    相关资源
    最近更新 更多