Rails4 - 如何在Rails应用程序中将image_tag作为参数传递?

时间:2015-06-01 23:42:59

标签: ruby-on-rails ruby-on-rails-4

我正在尝试将图片标记作为参数传递。

当我尝试像下面那样进行硬编码时,它的效果非常好。

messages_controller.rb

class MessagesController < ApplicationController      

  def create
  .
  .
  Pusher['private-'+pushid.id.to_s].trigger('new_message', 
  {:subject => "You have received a new message from <b>John</b>. 
  <img class=\"img-rounded\" 
  src=\"http://mywebsite.com/images/mini/missing.png\"  />" })
  .
  end

end

我尝试了以下操作以使其动态但我得到语法错误。我无法通过图片标记。

class MessagesController < ApplicationController      

  def create
  .
  .
  Pusher['private-'+pushid.id.to_s].trigger('new_message', 
  {:subject => "You have received a new message from <b>"+
  current_user.name.capitalize+"</b>." + 
  <%= image_tag(current_user.avatar.url(:mini)).gsub("\"", "'") %>  })
  .
  end

end

有人可以分享如何正确地做到这一点吗? 请帮助。感谢

1 个答案:

答案 0 :(得分:4)

这应该有效:

subject = "You have received a new message from "+
"<b>#{current_user.name.capitalize}</b>."+
"#{ActionController::Base.helpers.image_tag(current_user.avatar.url(:mini)).gsub('"', '\'')}"
Pusher['private-'+pushid.id.to_s].trigger('new_message',{:subject => subject})

在字符串中,您可以使用#{RUBY_CODE_HERE}插入ruby。

编辑:我将主题作为变量拉出来并使字符串成为多行,这样在堆栈溢出答案的宽度范围内更容易看到,你当然可以将它作为程序中的一行。