2014-06-30 27 views
1

我是新的鐵軌,我試着accept_nested_attributes_for函數。我正在創建庫存系統,並且正在使用accep_nested_attributes_for功能將多個訂單詳細信息附加到訂單。訂單還必須與商店位置相關聯。Rails 4 trouble與accept_nested_attributes_for

我遇到的問題是訂單正在創建,但沒有數據被傳遞到訂單明細表。

我的意見是以下:

訂單查看

<h1>Place An Order</h1> 

<%= form_for ([@location, @order]) do |f| %> 
    <p> 
    <%= f.label :customer_id %><br /> 
    <%= f.text_field :customer_id %> 
    </p> 
    <p> 
    <h3>Items</h3> 
    <%= f.fields_for :order_details do |builder| %> 
     <%= render 'order_detail_fields', :f => builder %> 
    <% end %> 
    </p> 

    <p><%= link_to_add_fields "Add Item", f, :order_details %></p> 

    <p> 
    <%= f.submit %> 
    </p> 
<% end %> 

Order_details_fields部分

<p class="fields"> 
    <%= f.label :item_id %><br /> 
    <%= f.text_field :item_id %></br> 
    <%= f.label :quantity %></br> 
    <%= f.text_field :quantity %></br> 
    <%= f.label :cost %></br> 
    <%= f.text_field :cost %></br> 
    <%= f.label :discount %><br /> 
    <%= f.text_field :discount %><br /> 
    <%= f.hidden_field :_destroy %> 
    <%= link_to_function "remove", "remove_fields(this)" %> 
</p> 

訂單控制器

class OrdersController < ApplicationController 

    def index 
     @orders = Order.all 
    end 

    def show 
     @order = Order.find(params[:id]) 
    end 

    def new 
     @order = Order.new 
     @location = Location.find(params[:location_id]) 
    end 

    def create 
     @location = Location.find(params[:location_id]) 
     @order = @location.orders.create(order_params) 
     #@order = @order.order_details.create 

     if @order.save 
      redirect_to @order 
     else 
      render :action => 'new' 
     end 
    end 

    private 
     def order_params 
      params.require(:order).permit(:customer_id, order_detials_attributes: [:id, :item_id, :quantity, :cost, :discount]) 
     end 

end 

訂單模式

class Order < ActiveRecord::Base 
    belongs_to :location 
    has_many :order_details, :dependent => :destroy 
    accepts_nested_attributes_for :order_details, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true 
end 

訂單詳細信息型號

class OrderDetail < ActiveRecord::Base 
    belongs_to :order 
end 

路線

resources :locations do 
     resources :orders 
end 

resources :orders do 
     resources :order_details 
end 

任何幫助,將不勝感激

+1

嘗試將此行添加到'new'方法'@ order.order_details.build'。 – Pavan

+0

你能發表你從表單提交中收到的'params'嗎? –

+0

嗨Rick我如何從表格提交中獲得參數 – user2121500

回答

0

構建

看起來一切都是我的權利 - 唯一的問題是概括的問題@Pavan,這是當你使用accepts_nested_attributes_for,你必須build的關聯對象,因此它可以在表單中使用:

#app/controllers/orders_controller.rb 
Class OrdersController < ApplicationController 
    def new 
     @location = Location.find parmas[:id] 
     @order = Order.find params[:id] 
     @order.order_details.build 
    end 
end 

雖然這看起來好像你有只有問題,可能還有其他的問題(在驗證model作爲示例(您沒有)

我和Pavan建議的唯一問題是,如果不建立關聯數據,則fields_for不會顯示在窗體上。如果您的字段正在顯示,則可能是另一個問題,將在params哈希中突出顯示

+0

好吧,我會研究這個,看看我能找到什麼。上面的Rick讓我從表單提交中發佈參數。我怎麼看這個? – user2121500