2

This code in the controller

av = ActionView::Base.new(Rails::Configuration.new.view_path)
av.extend ApplicationHelper
content = av.render(:file => "show", :locals => { :user => @user })

and the show.html.erb have the link_to helper , operation code error

undefined method `url_for' for nil:NilClass

I add av.extend ActionController::UrlWriter in the controller , still error

undefined method `default_url_options' for ActionView::Base:Class
s6520643
  • 107
  • 1
  • 8

3 Answers3

2

Try:

content = render_to_string(:file => "show", :locals => { :user => @user })
Valery Kvon
  • 4,438
  • 1
  • 20
  • 15
0

Usually, in Rails, when something is very hard, it is because you are not approaching the problem from an ideal angle. I can't really answer this question directly, other than to advise not to do this. Ideally, view logic should be in the view, and not the controller. With a few rare exceptions, like using a link_to helper in a flash message (which can be easily solved), these concerns should be separated. This does not seem like one of those exceptions. Instead, I would recommend one of the following (slightly more Rails-y) techniques:

Option 1:

It looks like you are trying to render the view for the show action. This can easily be accomplished by using render :action => 'show' (docs). This will not run the code for the action, just use that view.

Option 2

In the event that option 1 is not viable in your situation, you may alternatively consider some variation of the following technique. Render the default view, as normal. Move the existing content of the view into a partial, and your new content into a partial of its own. Then in your view, simply toggle the partial to render based off of an appropriate condition - the existence of @user, for this example: render :partial => @user ? 'new_content' : 'existing_content'. Depending on your application structure, it may be that this can be further simplified by just rendering the same partial from your show view and the view for the action referenced in the question.

I think keeping the various elements of an application isolated into their intended concerns not only makes this easier to develop and maintain by following the principle of least astonishment, but also usually makes the application much easier to test, as well. Sorry for not answering your question - hope this helps, anyway.

Community
  • 1
  • 1
Brad Werth
  • 17,411
  • 10
  • 63
  • 88
0

I suppose it was called outside controller so I do it this way in Rails 3:

av = ActionView::Base.new(Rails.configuration.paths["app/views"])
av.class_eval do
  include ApplicationHelper
  include Rails.application.routes.url_helpers
  default_url_options[:host] = 'yoursite.com'
  def protect_against_forgery?
    false
  end
end
@result = av.render(:file => "show", :locals => { :user => @user })
gertas
  • 16,869
  • 1
  • 76
  • 58