Ruby on rails 如何设置联接表';什么是额外属性?

Ruby on rails 如何设置联接表';什么是额外属性?,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,这些是我的模型 class Product has_many :line_items has_many :orders, :through => :line_items end class LineItem belongs_to :order belongs_to :product validates :quantity, presence: true end class Order has_many :line_items has_many :

这些是我的模型

class Product
  has_many :line_items
  has_many :orders, :through => :line_items
end

class LineItem 
  belongs_to :order
  belongs_to :product

  validates :quantity, presence: true
end

class Order
    has_many :line_items
    has_many :products, :through => :line_items
end

我可以做
@order.products你想手工做还是通过表格

如果手动操作,您只需在行项目的关系中查找产品并进行更新:

x = @order.line_items.last
x.quantity = 2
编辑:
Baconator507的答案是最快的

您需要直接创建行项目并指定其数量和产品

试试这样的

@product = Product.find(1)
@order.line_items.create(product_id: @product.id, quantity: 100)

您可以建立
@line\u项目
,而不是
@product
,然后将其附加到
@order
的行项目中

@line_item.quantity = 100
@line_item.product = Product.find(10)
@order.line_items << @line_item
@line_item.quantity=100
@行_item.product=产品.查找(10)

@order.line_items不需要连接表的额外属性,它已经存在了

Order#line_items # will return all information's you need
但是,如果您想按特定的顺序和数量退货,请尝试以下代码

首先,将
quantity
作为
attr\u访问器:quantity
添加到
Product.rb

然后,删除以下行
has_many:products,:to=>:line_items
in
Order.rb
create
products
方法

def products
  products_list = []
  line_items.each do |item|
    item.product.quantity = item.quantity
    products_list << item.product
  end
  products_list
end

order = Order.last
order.products # will return list of products with quantity attribute 
def产品
产品清单=[]
行_项。每个do |项|
item.product.quantity=item.quantity

产品列表我必须做
行项目。构建
而不是
行项目。创建
以使其正常工作,否则这是最简单的解决方案。