首页 > 解决方案 > 未创建帖子,无法加载图像。铁轨上的红宝石

问题描述

有人可以帮忙吗。试图在帖子中添加图片,但帖子没有创建。错误:无法将图像解析为 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

标签: ruby-on-railsruby

解决方案


您需要将表单配置为多部分表单https://guides.rubyonrails.org/form_helpers.html#uploading-files

<%= form_for Post.new, multipart: true do |f| %>

如果表单不是多部分的,它将不会发送文件。


推荐阅读