ruby-on-rails 无法在rails 7中以评论形式上传图像

xytpbqjk  于 11个月前  发布在  Ruby
关注(0)|答案(1)|浏览(138)

这是我的表格:

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

字符串
以下是控制器创建操作:

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


以下是商店评论模型:

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


以下是商店注解参数:

private

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


控制台显示什么是因为“放置”:

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


它不输出有关图像的任何信息

nsc4cvqm

nsc4cvqm1#

根据Rails Guide https://guides.rubyonrails.org/v7.1/form_helpers.html
文件上传时最重要的一点是,渲染表单的enctype属性必须设置为“multipart/form-data”。如果在form_with中使用file_field,这将自动完成。您也可以手动设置该属性:
<%= form_with url:“/uploads”,multipart:true do|形式|%> <%= file_field_tag:picture %><% end %>
所以要么加上

enctype="multipart/form-data"

字符串
或使用所提供的帮助。

相关问题