Question

I know there are alot of these kinds of posts on SO, and I think Ive read and tried each of them, all without success.

I have Post and Image models that I need to work together with a many to one relationship.

class Post < ActiveRecord::Base
  has_many :images
end

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

Here is the post_parms declaration in my posts controller, which includes all of the fields in my image model migration.

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

and here is my post creation form where, I hope to allow multiple image asset creation with each post.

<%= 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>

Despite repeated effort and reading every post I can find on this topic, I'm still getting:

Unpermitted parameters: image

The trouble here is that this error provides no clue where to start looking for the problem. Since Im not really sure where to look next I thought I would post it here looking for more professional opinions.

Was it helpful?

Solution

Update the Post model as below:

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

This way upon form submission you would receive the image attributes in key images_attributes and not image which you are currently receiving which is causing the warning as Unpermitted parameters: image

As you have 1-M relationship between Post and Image

You need to update post_params as below:

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

Use images_attributes (Notice plural images) and NOT image_attributes (Notice singular image)

And change fields_for in your view as

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

Use images (Notice plural) and NOT image (Notice singular)

UPDATE

To resolve uninitialized constant Post::Image error

Update Image model as below:

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

Also, suggested to remove multiple: :true from

<%= ff.file_field :file, multiple: true %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top