尝试在模型内部为字符串变量rails 5创建链接

麦克

我的消息模型中有一个用于创建通知的方法,当创建通知时,我还在为字符串变量内容创建内容。这就是该方法的外观。

 def create_notification

  if self.conversation.sender_id == self.user_id
    sender = User.find(self.conversation.sender_id)
    Notification.create(content: "New message from #{sender.fullname}", user_id: self.conversation.recipient_id)
  else
    sender = User.find(self.conversation.recipient_id)
    Notification.create(content: "New message from #{sender.fullname}", user_id: self.conversation.sender_id)
  end
end

我想将内容“来自#{sender.fullname}的新消息”全部链接到converstations_path。我尝试了以下方法。

        Notification.create(content: "<a href="/converstions">New message from #{sender.fullname}</a>", user_id: self.conversation.recipient_id)

        Notification.create(content: "<%= link_to 'New message from #{sender.fullname}', conversations_path %>", user_id: self.conversation.recipient_id)

结果是它将呈现引号内的所有内容,而忽略html或link_to帮助器。如何建立连结?

我正在_notification.html.erb内部呈现notification.content,这是文件的样子

<strong><%= notification.content %></strong>
<span class="pull-right"><%= notification.created_at.to_formatted_s(:short) %></span>
格里西

解决此问题的一种方法是在您的通知模型中添加一个字段,例如srcsrc将是您希望将用户发送到的链接。然后,无论何时向用户呈现此通知,都可以在notification.src使用link_to

这是我推荐的方法,但是我相信您也可以使用类似notification.content.html_safe的方法来解析+渲染HTML,而不仅仅是渲染HTML。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章