rails 4 unpermitted params嵌套表单

时间:2014-05-03 21:43:59

标签: ruby-on-rails ruby-on-rails-4 carrierwave nested-forms

我知道在SO上有很多这样的帖子,我想我已经阅读并尝试过各自的帖子,但都没有成功。

我有Post和Image模型,我需要与多对一关系一起工作。

class Post < ActiveRecord::Base
  has_many :images
end

class Image < ActiveRecord::Base
  belongs_to :post
  mount_uploader :file, images_uploader
end

这是我的帖子控制器中的post_parms声明,其中包含我的图像模型迁移中的所有字段。

private
 def post_params
  params.require(:post).permit(:title, :content, image_attributes: [:id, :post_id, :file])
end

这是我的帖子创建表单,我希望允许每个帖子创建多个图像资源。

<%= form_for @post, html: {class: "pure-form pure-form-stacked"} do |post| %>

<%= post.fields_for :image, :html => { :multipart => true } do |image| %>
    <%= image.label :file, "Upload Image:" %>
    <%= image.file_field :file, multiple: true %>   
<% end %>

<fieldset class="post-form">
    <%= post.label :title %>
    <%= post.text_field :title %>

    <%= post.label :content %>
    <%= post.text_area :content, :class => "redactor", :rows => 40, :cols => 120 %>
</fieldset>

<div class = "button-box">
    <%= post.submit class: "pure-button pure-button-primary" %>
    <%= link_to "Cancel", posts_path, :class => "pure-button" %>
</div>

尽管经过多次努力并阅读了我在这个主题上可以找到的每篇文章,但我仍然得到:

Unpermitted parameters: image

这里的问题是这个错误没有提供从哪里开始寻找问题的线索。由于我不确定下一步该向下看,我想我会在这里发布,寻找更专业的意见。

1 个答案:

答案 0 :(得分:2)

更新Post模型,如下所示:

class Post < ActiveRecord::Base
  has_many :images
  accepts_nested_attributes_for :images ## Add this
end

这样,在表单提交时,您会收到当前正在接收的密钥images_attributes而不是image的图片属性,这会导致警告为Unpermitted parameters: image

1-M relationshipPost之间Image

您需要更新post_params,如下所示:

def post_params
  params.require(:post).permit(:title, :content, images_attributes: [:id, :post_id, :file])
end

使用images_attributes注意多个图片)而不是image_attributes注意奇异图片

并在视图中将fields_for更改为

<%= post.fields_for :images, :html => { :multipart => true } do |image| %>

使用images通知复数)而非image通知单数

<强>更新

解决uninitialized constant Post::Image错误

更新Image模型如下:

class Image < ActiveRecord::Base
  belongs_to :post
  ## Updated mount_uploader
  mount_uploader :file, ImagesUploader, :mount_on => :file
end

另外,建议从

中删除multiple: :true
<%= ff.file_field :file, multiple: true %>
相关问题