ruby-on-rails - 未创建帖子,无法加载图像。铁轨上的红宝石
问题描述
有人可以帮忙吗。试图在帖子中添加图片,但帖子没有创建。错误:无法将图像解析为 URL:to_model 委托给附件,但附件为零。
问题显示在这一行:
<%= image_tag post.image , class: 'main-image' %>
我有这个表格:
<%= form_for Post.new do |f| %>
<div class="form-group">
<%= f.text_field :description %>
</div>
<div class="form-group">
<%= f.file_field :image %>
</div>
<div class="form-group">
<%= f.text_field :user_id, value: current_user.id, class:'d-none'%>
</div>
<br>
<div class="text-center">
<%= f.submit 'Create Post', class: 'btn btn-primary' %>
</div>
<% end %>
这在我的 html 文件中
<% @posts.each do |post| %>
<section class="post">
<div class="user">
<div class="avatar">
<img src="user_avatar.jpg">
</div>
<div class="username">
<%= post.user.username %>
</div>
</div>
<%= image_tag post.image , class: 'main-image' %>
<div class="description">
<%= post.description %>
</div>
</section>
<% end %>
</div>
belongs_to :user
has_one_attached :image
validate :image_presence
def image_presence
errors.add(:image, "can't be blank") unless image.attached?
end
end
------
post.rb
class PostsController < ApplicationController
def create
Post.create(post_params)
redirect_to root_path
end
private
def post_params
params.require(:post).permit(:description, :image, :user_id)
end
end
------
post_controller
test:
service: Disk
root: <%= Rails.root.join("tmp/storage") %>
local:
service: Disk
root: <%= Rails.root.join("storage") %>
--------
storage.yml
在 development.rb 中有这个
config.active_storage.service = :local
解决方案
您需要将表单配置为多部分表单https://guides.rubyonrails.org/form_helpers.html#uploading-files
<%= form_for Post.new, multipart: true do |f| %>
如果表单不是多部分的,它将不会发送文件。
推荐阅读
- ios - iPhone 未从 AppleWatch 接收 applicationContext
- python-3.x - python重新打开并将数据写入现有文件(文件名由用户先前的输入给出)
- java - 如何在 Spring 的单个事务中使用多个数据源(一个用于读取,另一个用于写入)?
- javascript - Javascript:
如果找到特殊字符则添加 - c++ - 如何检查模板参数化回调函数签名是一种
- c# - 按 smalldatetime 字段排序在 SQL Server 和 C#(实体框架)中产生不同的结果
- php - 课堂内准备好的语句不起作用
- java - 如何修复被忽略的嵌入式对象中的验证约束?
- apache-kafka - logstash kafka 输入具有不同编解码器的多个主题
- c# - 在方法调用 C# WPF 之后设置组合框所需的索引