使用ActiveRecord正确连接Rails中的表

时间:2014-07-28 11:42:48

标签: ruby-on-rails rails-activerecord ruby-on-rails-4.1

我的模特:     模型/ organization.rb

class Organization < ActiveRecord::Base
  has_many :organization_payments
end

models/organization_payment.rb

class OrganizationPayment < ActiveRecord::Base
  belongs_to :organization
end

组织表中包含以下列:

id
org_name

organization_payments中包含以下列:

organization_id
amount

当我这样做时:

@organization_payments = OrganizationPayment.joins(:organization)
.where("organization_payments.organization_id = organizations.id")

我只获取organization_payments表中的列,而不是组织表中的org_name列。连接语句的正确语法是什么?

警告:

请注意,如果两个表都有一个id列(并且它们应该),则需要具体说明哪一个包含在哪一个,否则您将在Index视图中找到错误的链接。

2 个答案:

答案 0 :(得分:3)

Marek Lipka的回答很好,但我也建议你看一下代表。如果您将OrganizationPayment修改为:

class OrganizationPayment < ActiveRecord::Base
  belongs_to :organization
  delegate :org_name to: :organization
end

然后,您就可以调用organization_payment.org_name来检索组织名称。如果要遍历许多OrganizationPayment对象,请使用 includes 以确保委派不会为每个查找生成新的SQL调用。所以:

OrganizationPayment.includes(:organization).each{|payment| puts payment.org_name}

答案 1 :(得分:1)

在这种情况下,您应该使用select,如下所示:

@organization_payments = OrganizationPaiment.select('*, organizations.org_name as organization_name').joins(:organization)
通过这种方式,org_name值可以像这样访问:

organization_payment.organization_name

越多&#34; Rails&#34;实现相同目标的方法是使用includes预加载关联的组织:

@organization_payments = OrganizationPayment.includes(:organization)

并简单地使用ActiveRecord关联,如下所示:

organization_payment.organization.org_name