【问题标题】:Rails ActiveRails joins - table name in plural/singularRails ActiveRails 连接 - 复数/单数的表名
【发布时间】:2018-03-25 22:13:41
【问题描述】:

我有以下使用 ActiveRecord 的“查询”:

Product.joins(product_attr_vals: [attr_val: [:attr]])
       .joins(:product_model)
       .where(product_models: {id: @product_model.id}, attrs: {id: attr.id})
       .distinct
       .count

我无法理解为什么有时,在 joins() 中,rails 接受复数形式的表名而其他人接受单数形式。

  • product_attr_vals: (单数时无效 -> product_attr_val)
  • attr_val:
  • :attr
  • :product_model

一些信息:

models/product_model_attr_val.rb

class ProductModelAttrVal < ApplicationRecord
  validates :product_model_id, uniqueness: { scope: :attr_val_id }

  belongs_to :product_model
  belongs_to :attr_val
end

db/migrate/db_creation.rb

create_table :product_model_attr_vals do |t|
  t.references :product_model, null: false, foreign_key: true
  t.references :attr_val, null: false, foreign_key: true

  t.timestamps
end

【问题讨论】:

标签: ruby-on-rails database join activerecord


【解决方案1】:

何时使用单数或复数的答案在于关联的名称。通常has_many 关联以复数命名,而belongs_to 关联以单数命名。在后台构建查询时 ActiveRecord 将确保始终使用正确的表名(复数)。在 Rails 中有“约定优于配置”的概念,这意味着很多东西都有预定义的方法,可以开箱即用。例如。联系belongs_to :product。 ActiveRecord 将在表products 中查找列product_id 并使用它来加载产品。另一个例子,has_many :products - ActiveRecord 将查找一个名为products 的表并假设它有一个列your_model_id。因此它将为您的模型实例加载所有产品。

回到您的问题,何时使用单数或复数。如果您不确定,请检查相应模型中的关联定义。一般来说,has_many 关联使用复数,belongs_to 关联使用单数。以下是两个模型的示例:

class Employee
  has_many :tasks
end

class Task
  belongs_to :employee
end

这里有一些joins 的例子:

Employee.joins(:tasks) # plural due to has_many 
Task.joins(:employee) # singular due to belongs_to

希望对您有所帮助!

【讨论】:

  • 非常感谢您的出色回答!我快疯了,以为我做错了什么。
猜你喜欢
  • 2013-02-28
  • 1970-01-01
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 2012-03-01
相关资源
最近更新 更多