开发者

How do I pass html based on ruby code / erb into a method expecting a string in Rails 3?

The following code doesn't work because I can't access the helper inside of a controller:

string << "#{has shared link_to @review.title, @review}"
开发者_如何转开发

But within the action (or possibly a method in the model) I still need to pass the html that would be generated from this.

I tried the template instance but doesn't work in Rails 3


Just as a basic example, say you have:

app/messages_controller.rb and

helper/messages_helper.rb

In you messages_helper.rb you may have something like what you've suggested.

#Also you should use = instead of <<
#You can only use << on a variable that has already been initialised
#a =  "hello "  #=> "hello"
#a << "world"   #=> "hello world"
#b << "whatevs" #=> ERROR

def dummy_helper_method
    @html_string = "has shared #{link_to @review.title, @review}"
    @html_string
end

Then in your messages_controller.rb in any of your methods you can call your new dummy_method and you'll now get access to your @html_string instance variable

def index
    dummy_helper_method

    #you can now access your @html_string variable from inside this index method
end

Just as a note though, this isn't the right way to do this. You shouldn't call it in your controller unless you're trying to do something fairly specific with it which it doesn't look like you are. If you're trying to get it out into your view so that you can display it, you can actually call your helper method that you've just created in any of your messages' view files (views/messages/anything_in_here.html.erb) rather than calling it in your controller.

For example:

#views/messages/edit.html.erb
<%= dummy_helper_method %>

Anyways, hope it helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜