提问人:John Sall 提问时间:11/8/2023 更新时间:11/8/2023 访问量:24
无法在 Rails 7 中以评论形式上传图像
cannot upload image in comment form in rails 7
问:
这是我的表格:
<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
它不输出有关图像的任何信息
答:
1赞
zaphodbln_
11/8/2023
#1
根据 Rails Guide https://guides.rubyonrails.org/v7.1/form_helpers.html:
文件上传时要记住的最重要的一点是 呈现表单的 enctype 属性必须设置为 “multipart/form-data”。如果您使用 file_field在form_with内。您还可以设置属性 手动地:
<%= form_with url: “/uploads”, multipart: true do |form|%> <%= file_field_tag :p icture %> <% 结束 %>
所以要么添加
enctype="multipart/form-data"
添加到您的表单标签或使用提供的帮助程序。
评论