2016-09-30 42 views
0

我無法弄清楚我做錯了什麼。我有兩個型號:Rails 4 Has_one嵌套窗體 - 錯誤無限參數

class Product < ActiveRecord::Base 
    has_one :review, dependent: :destroy 
    accepts_nested_attributes_for :review, allow_destroy: true 
end 
class Review < ActiveRecord::Base 
    belongs_to :product 
end 

他們有一個has_one關係。數據庫在評論表中有product_id列。

我的控制器是直接在新的(@ product = Product.new)和編輯操作沒有任何東西。下面是我的強烈PARAMS:

def product_params 
    params.require(:product).permit(:name, ..., review_attributes: [:id, :rating, :text, :author, :name]) 
end 

我的格式如下:

<%= form_for(@product, :html => {multipart: true, :class => "form-horizontal"}) do |f| %> 
... 

    <%= f.fields_for :review do |ff| %> 
     <%= ff.hidden_field :author, :value => 'Yes' %> 
      <%= ff.label :rating, "Enter a Rating" %> 
      <%= ff.number_field :rating, class: "form-control input-md", min: 0, max: 5, step: 0.5 %> 
      <%= ff.label :name, "Title of Review" %> 
      <%= ff.text_field :name, class: "form-control input-md" %> 
      <%= ff.label :text, "Review Description" %> 
      <%= ff.text_area :text, class: "form-control" %> 
    <% end %> 
     <%= f.submit "Create Product", :class => 'btn btn-default btn-lg' %> 
<% end %> 

我想不通爲什麼當我在模型中accepts_nested_attributes嵌套表格沒有出現,不管是不是我需要accept_nested_attributes,爲什麼當我沒有accept_nested_attributes並提交表單時,我得到一個錯誤,提示「未經許可的參數:審查」。任何幫助是極大的讚賞。

+0

也許,你需要建立審查對象在控制器中的視圖呈現前...你在那裏有的其他東西看起來對我來說還好,我認爲當表格呈現時你錯過了相關的對象......我回答你接受這個問題。 – Eric

回答

1

在控制器中,嘗試建立審查對象在被渲染的形式方法...

def new 
    @product = Product.new 
    @product.build_review 
end 
+0

這工作..有關爲什麼的任何想法?我認爲這個accept_nested_attributes負責構建? –

+0

nope,你必須建立你正在接受屬性的對象......'<%= f.fields_for:review do | ff | %>'那條線......你在說什麼,這裏是'review'對象的字段......你必須讓這個對象在內存中建立......有意義嗎? – Eric

+0

是的。我遇到的另一個問題是控制器中的編輯操作。評論對象的信息不會填充表單域。那裏有任何想法?對,不,我的控制器只是(def編輯結束)。 –