我在哪里添加代码来操作 Rails 中博客文章的文本



这是在views/posts/show.html.erb文件中对我有用的代码:

<% require 'rmmseg' %>
<% RMMSeg::Dictionary.load_dictionaries %>
<% text = "你好" %>
<% algor = RMMSeg::Algorithm.new(@post.content) %>
<% loop do %>
    <% tok = algor.next_token %>
    <% break if tok.nil? %>
    <% text2 = tok.text.force_encoding('UTF-8') %>
    <%= "#{text2}" %>
<% end %>

我是 rails 的新手,所以我需要帮助知道将此代码或类似代码放在框架中的哪个位置,以便它将帖子与数据库中的空格一起保存。它应该在控制器中吗?如果是这样,我该怎么做?

我正在尝试并失败了:

def create
    @post = Post.new(params[:post])
require 'rmmseg'
  RMMSeg::Dictionary.load_dictionaries
    algor = RMMSeg::Algorithm.new(@post.content)
    loop do
    tok = algor.next_token
    break if tok.nil?
    text2 = tok.text.force_encoding('UTF-8')
    @post.content = "#{text2}"
    end
    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

我显然已经知道我在做什么了。

我拨打了 Rails 热线,他们给了我一个提示,让我使用回调(before_save、after_save等)将其放入模型中。

这对我有用。

最新更新