Action text(Trix):无法在Rails中富文本中添加图像(“附加文件”未保存)
创始人
2024-07-23 18:31:35
0

要在Rails中使用Action Text(Trix)富文本编辑器添加图像,需要确保附加文件已保存。以下是一个可能的解决方法:

  1. 在你的模型中,确保使用has_one_attachedhas_many_attached方法来创建附加文件的关联。例如,如果你的模型名为Post,你可以在app/models/post.rb中添加以下代码:
class Post < ApplicationRecord
  has_one_attached :image
end
  1. 在你的视图中,使用trix-editor标签来创建富文本编辑器。确保将附加文件的URL作为data-direct-upload-url属性传递给trix-editor标签。例如,在app/views/posts/_form.html.erb中,你可以添加以下代码:
<%= form_with(model: post, local: true) do |form| %>
  <%= form.rich_text_area :content %>
  <%= form.file_field :image, direct_upload: true %>
  <%= form.submit %>
<% end %>
  1. 在你的控制器中,确保在创建或更新记录时,将附加文件与记录关联起来。例如,在app/controllers/posts_controller.rb中,你可以添加以下代码:
class PostsController < ApplicationController
  def create
    @post = Post.new(post_params)
    @post.image.attach(params[:post][:image])
    if @post.save
      redirect_to @post
    else
      render 'new'
    end
  end

  def update
    @post = Post.find(params[:id])
    @post.image.attach(params[:post][:image])
    if @post.update(post_params)
      redirect_to @post
    else
      render 'edit'
    end
  end

  private

  def post_params
    params.require(:post).permit(:content)
  end
end

请注意,上述示例中的代码是基于Rails 6和Active Storage的。确保你已经在你的应用程序中正确配置和安装了Active Storage。

以上解决方法应该可以帮助你在Rails中使用Action Text(Trix)富文本编辑器成功添加图像。

相关内容

热门资讯

Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...
Aksnginxdomainb... 在AKS集群中,可以使用Nginx代理服务器实现根据域名进行路由。以下是具体步骤:部署Nginx i...
AddSingleton在.N... 在C#中创建Singleton对象通常是通过私有构造函数和静态属性来实现,例如:public cla...
Alertmanager中的基... Alertmanager中可以使用repeat_interval选项指定在一个告警重复发送前必须等待...