我想使用订单表格从下表中的:quantity
中存储值,但我不知道如何针对此特定表格执行此操作。
create_table "order_items", force: true do |t|
t.integer "item_id"
t.integer "order_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "quantity"
t.decimal "price"
end
关系如下
has_many :order_items
has_many :items, :through => :order_items
has_many :order_items
has_many :orders, :through => :order_items
belongs_to :item
belongs_to :order
答案 0 :(得分:2)
您需要使用accepts_nested_attributes_for
,然后在Rails中使用nested form
:
#app/models/order.rb
Class Order < ActiveRecord::Base
has_many :order_items
has_many :items, :through => :order_items
accepts_nested_attributes_for :order_items
end
这意味着您必须build
order_item
对象才能发送数据,以便您的表单可以使用f.fields_for
方法处理关联数据,像这样:
#app/controllers/orders_controller.rb
Class OrdersController < ApplicationController
def new
@order = Order.new
@order.order_items.build
end
def create
@order = Order.new(order_params)
@order.save
end
private
def order_params
params.require(:order).permit(:order, :params, order_items_attributes: [:quantity])
end
end
#app/views/orders/new.html.erb
<%= form_for @order do |f| %>
<%= f.fields_for :order_items do |o| %>
<%= o.text_field :quantity %>
<% end %>
<% end %>