Ruby on rails Rails4-如何在Rails应用程序中将图像_标记作为参数传递?

Ruby on rails Rails4-如何在Rails应用程序中将图像_标记作为参数传递?,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我正在尝试将图像标记作为参数传递 当我尝试像下面这样硬编码时,它工作得非常好 消息\u controller.rb class MessagesController < ApplicationController def create . . Pusher['private-'+pushid.id.to_s].trigger('new_message', {:subject => "You have received a new message f

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

当我尝试像下面这样硬编码时,它工作得非常好

消息\u 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 messages控制器“您收到了来自John的新消息。
" })
.
结束
结束
我尝试了以下方法使其动态化,但出现语法错误。我无法通过图像标签

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
class messages控制器“您已收到来自的新邮件”+
当前_user.name.capitalize+“+
这应该起作用:

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})
subject=“您收到了来自的新消息”+
“#{current_user.name.capitalize}”+
“{ActionController::Base.helpers.image_标记(当前用户.avatar.url(:mini)).gsub(''','\''')”
Pusher['private-'+pushid.id.to_s].trigger('new_message',{:subject=>subject})
在字符串中,您可以使用
{RUBY\u code\u HERE}
插入RUBY


编辑:我将主题作为变量取出,并将字符串改为多行,以便在stackoverflow答案的宽度内更容易看到,您当然可以将其保留为程序中的一行。

语法错误是什么?此代码位于何处?在.erb文件或.js文件或其他地方?@neuronaut抱歉没有提供文件名。谢谢你的提问。我更新了这个问题。我想现在我知道它为什么不起作用了。我正在尝试在控制器中使用image_标记。@LovingRails好的,问题是你不需要在ruby代码中使用
分隔符(控制器就是ruby代码)。这些分隔符用于.erb文件,其中它们标记插入文件的ruby的开始和结束。无论如何,@Exupery的答案应该是这样做的。但是,根据经验,在控制器中创建HTML不是一个好主意——这就是视图的用途。感谢@neuronaut提供的信息。但是该操作没有视图。I在post操作期间执行。这是路由。messages-post-/messages(:格式)-messages#Create非常感谢。我想如果有人在没有学习ruby的情况下学习rails,就会发生这种情况。我刚刚意识到代码在controller中。因此我得到image_标记错误。在将ActionController::Base.helpers作为image_标记的前缀添加到image_标记后,它工作得非常好。请确认是否可以使用它#{ActionController::Base.helpers.image_标记(当前用户.avatar.url(:mini)).gsub(“\”,““”)}”?任何有效的Ruby代码都可以放入
{}
块中,这样应该可以工作-但您需要在gsub中转义引号(或使用单引号),我将用不同的引号编辑答案。如果我不使用ActionController::Base,我将得到#的未定义方法“image_tag”。helpers@LovingRails很抱歉,当我更新了引号的答案时,我没有添加
ActionController::Base.helpers
-只是在中编辑了它。