Reputation: 1579
I currently save code like below in my user model.
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
I save these messages in my model, and print them out in the view by just calling User.find(params[:id]).messages in the controller.
The actual model code is much longer, as there are many unique messages based on different scenarios.
While this works, I would now like to add a link_to
to objects that are mentioned in the messages.
For the first message, I want to save it so that when I send it to the view, it's in the form of
Hello <%= link_to user.name, user_path(user.id) %>, you now have <%= link_to user.points, leaderboard_path %> points!
I tried the below, but it doesn't work.
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
How can I save erb in my string?
Upvotes: 0
Views: 144
Reputation: 29349
How about this? Use html tags instead of using 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
And in your view, Just do
<%= user.message %>
Upvotes: 1
Reputation: 2188
This is not a very good pratice.
You can like:
class Model < ActiveRecord::Base
include Rails.application.routes.url_helpers
def example
ActionController::Base.helpers.link_to user.name, user
end
end
But using a helper or a erb template to show this to the user seems the best way.
Upvotes: 1