Rails 7:上传图像到富文本区域未显示

问题描述 投票:0回答:1

我在 ruby on Rails 的主页上关注了这个视频:https://rubyonrails.org/。这是我的步骤

rails new demo
rails generate scaffold post title:string content:text
rails db:migrate
rails server
http://localhost:3000/
http://localhost:3000/posts
http://localhost:3000/posts/1
http://localhost:3000/posts/1/edit
http://localhost:3000/posts/new

文件

D:\2024_04_29\demo\app\views\layouts\application.html.erb

<!DOCTYPE html>
<html>
<head>
  <title>Demo</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <%= csrf_meta_tags %>
  <%= csp_meta_tag %>

  <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
  <link rel="stylesheet" href="https://cdn.simplecss.org/simple.min.css">
  <%= javascript_importmap_tags %>
</head>

<body>
<%= yield %>
</body>
</html>

http://localhost:3000/posts.json http://localhost:3000/posts/2.json

验证

文件

D:\2024_04_29\demo\app\models\post.rb

class Post < ApplicationRecord
    validates_presence_of :title
end
rails console
rails c
Post.first
Post.create! title:”From the console”, content: “Nice!”
Post.where(created_at: Time.now.all_day).to_sql

Post.where(created_at: Time.now.all_day)


irb(main):008> Post.where(created_at: Time.now.yesterday.all_day)

irb(main):008> Post.where(created_at: Time.now.yesterday.all_day).to_sql
rails action_text:install
bundle
rails db:migrate

文件

D:\2024_04_29\demo\app\models\post.rb

class Post < ApplicationRecord
    validates_presence_of :title
    has_rich_text :content
end

文件

D:\2024_04_29\demo\app\views\posts\_form.html.erb

<%= form_with(model: post) do |form| %>
  <% if post.errors.any? %>
    <div style="color: red">
      <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
        <% post.errors.each do |error| %>
          <li><%= error.full_message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div>
    <%= form.label :title, style: "display: block" %>
    <%= form.text_field :title %>
  </div>

  <div>
    <%= form.label :content, style: "display: block" %>
    <%= form.rich_text_area :content %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>

enter image description here

我检查了数据库

enter image description here

源代码:https://github.com/donhuvy/rails7demo

为什么我的图片没有显示?怎么解决?

ruby-on-rails ruby
1个回答
0
投票

问题是您将列

posts.content
创建为
text
数据类型

动作文本不需要模型表中的列。动作文本是某种模型,通过

record_id
record_type

使用多态关联与其他模型关联

首先,您需要使用命令为操作文本创建(如果不存在)表格、样式和部分

bin/rails action_text:install

我不喜欢 Rails 生成器,但你的第一个命令应该是

bin/rails g scaffold post title:string content:rich_text

(富文本,不仅仅是文本)

此命令不会创建新列,只是向模型、视图等添加

has_rich_text
符号。

您需要删除

posts.content

另请注意,如果您转换图像,您将需要系统库(默认为 libvips)

了解更多:

https://edgeguides.rubyonrails.org/action_text_overview.html

© www.soinside.com 2019 - 2024. All rights reserved.