在模型中保存使用ERB数据的字符串



i当前在用户模型中保存下面的代码。

User.where(type: "supercool").each do |user|
    if user.score == 100
        user.message = "Hello #{user.name}, you now have #{user.points} points!".html_safe
    elsif user.address == "New York"
        user.message = "You live in the same town as #{Person.where(address:"New York").first.name}"
    user.save
end

我将这些消息保存在我的模型中,然后只需调用user.find(params [:id])。控制器中的消息。

实际的模型代码更长,因为基于不同方案的许多唯一消息。

当它起作用时,我现在想将link_to添加到消息中提到的对象中。

对于第一条消息,我想保存它,以便当我将其发送到视图时,它以

的形式
Hello <%= link_to user.name, user_path(user.id) %>, you now have <%= link_to user.points, leaderboard_path %> points!

我尝试了以下操作,但它不起作用。

User.where(type: "supercool").each do |user|
    if user.score == 100
        user.message = "Hello #{link_to user.name, user}, you now have #{link_to user.points, leaderboard_path} points!".html_safe
    user.save
end

如何将ERB保存在我的字符串中?

这怎么样?使用HTML标签而不是使用link_to

  User.where(type: "supercool").each do |user|
    if user.score == 100
      user.message = "Hello <a href=#{Rails.application.routes.url_helpers.user_path(user)}>#{user.name}</a>, you now have <a href=#{Rails.application.routes.url_helpers.leaderboard_path}>#{user.points}</a> points!".html_safe
      user.save
   end
 end

,在您的看来,只需做

<%= user.message %>

这不是一个很好的pratice。

您可以喜欢:

class Model < ActiveRecord::Base
  include Rails.application.routes.url_helpers
  def example
    ActionController::Base.helpers.link_to user.name, user
  end 
end

但是使用助手或ERB模板向用户显示这似乎是最好的方法。