2016-09-30 102 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编辑结束)。 –