cannot upload image in comment form in rails 7

45 Views Asked by At

This is my form :

<form action= "<%= store_post_store_comments_path(params[:id]) %>" method="post">
    <div class='field'>
        <textarea name="comment[comment]" id="" rows=6" cols="20"></textarea>
    </div>

        <span class='image'>
                <input accept="image/jpeg,image/gif,image/png" type="file" name="comment[image]" id="" />
        </span>

    <input type="submit" value="Submit">
</form>

This is the controller create action :

def create

    @comment = current_user.store_comment.new(store_comment_params)
    @comment.image.attach(params[:comment][:image])

    puts "for console debugging"
    puts store_comment_params
    puts params[:comment][:comment]
    puts params[:store_post_id]
    puts params[:comment][:image]

        if @comment.save
          flash[:info] = 'your comment has been created'
          redirect_to request.referrer
        end
        
 end

This is the store comment model :

class StoreComment < ApplicationRecord
  belongs_to :store_post
  belongs_to :user
  has_one_attached :image
end

This is the store comment params :

private

    def store_comment_params
      params
      .require(:comment)
      .permit(:comment, :image)
      .merge(store_post_id: params[:store_post_id])
      
    end

What console show because the "puts":

{"comment"=>"this is a test image", "store_post_id"=>"26"}
this is a test image
26

it doesn't output any information about the image

1

There are 1 best solutions below

0
On BEST ANSWER

According to the Rails Guide https://guides.rubyonrails.org/v7.1/form_helpers.html:

The most important thing to remember with file uploads is that the rendered form's enctype attribute must be set to "multipart/form-data". This is done automatically if you use a file_field inside a form_with. You can also set the attribute manually:

<%= form_with url: "/uploads", multipart: true do |form| %> <%= file_field_tag :picture %> <% end %>

So either add

enctype="multipart/form-data"

to your Form-Tag or use the provided helpers.