Rails - 通过关联存储值

时间:2014-06-06 03:17:22

标签: ruby-on-rails ruby-on-rails-4 associations simple-form

我想使用订单表格从下表中的: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

OrderItem模型

belongs_to :item
belongs_to :order

1 个答案:

答案 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 %>