【问题标题】:Best way to make an HABTM association via console通过控制台建立 HABTM 关联的最佳方式
【发布时间】:2015-06-08 21:35:19
【问题描述】:

我有这种情况:

class Order < ActiveRecord::Base
  has_and_belongs_to_many :products
end

class Product < ActiveRecord::Base
  has_and_belongs_to_many :orders
end

class CreateJoinTableOrdersProducts < ActiveRecord::Migration
  def change
    create_join_table :orders, :products do |t|
      t.index [:order_id, :product_id]
      t.index [:product_id, :order_id]
      t.decimal :price, precision: 8, scale: 2
      t.integer :quantity, default: 1      
    end
  end
end

现在,我需要使用命令行添加一些记录:

这很好用:

Order.first.products << Product.first

但是,我需要添加更多字段,例如:pricequantity...

我该怎么做?

【问题讨论】:

  • 在这种情况下你应该使用has_many :through
  • 我认为你会反对 Rails。 :) 阅读stackoverflow.com/questions/2327849/…。现在,如果您按照链接答案的说明进行操作,您将从 Rails free 获得工具。

标签: ruby-on-rails ruby


【解决方案1】:

Rails 具有 association.create.build 方法,可让您动态创建关联模型:

Order.first.products.create(price: 999)

但正如@test 所指出的,当连接表包含自己的数据时,您需要使用has_many_through 而不是has_and_belongs_to_many

has_and_belongs_to_many 用于直接的多对多关系。没有直接的方法可以在 HABM 关系中获取附加数据,例如 pricequantity,该关系只是建立在具有连接模型 ID 的连接表上。 rails guides 很好地解释了这一点。

class Order < ActiveRecord::Base
  has_many :row_items
  has_many :products, though: :row_items
end

class Product < ActiveRecord::Base
  has_many :row_items
  has_many :orders, though: :row_items
end

class RowItem < ActiveRecord::Base
  belongs_to :product
  belongs_to :order
end

您还需要创建正确的表:

rails g migration CreateRowItem product:belongs_to order:belongs_to price:decimal ...

然后您可以通过以下方式创建关联记录:

Order.first.row_items.create(price: 999, product: product)

【讨论】:

  • 我编辑了问题,包括您的关系定义不正确。
  • 因为has_many though 就是这样工作的。 has_many :row_items 定义了实际的关系。 has_many :products, though: :row_items 告诉 rails 通过 row_items 查找产品。 guides.rubyonrails.org/…
  • 你能解释一下为什么你使用 has_many :through 而不是 has_and_belongs_to_many 吗?
  • has_and_belongs_to_many 用于直接的多对多关系。没有直接的方法可以在 HABM 关系中获取额外的数据,例如 pricequantity,该关系只是建立在具有连接模型 ID 的连接表上。导轨指南很好地解释了这一点guides.rubyonrails.org/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-17
  • 1970-01-01
相关资源
最近更新 更多