Question

I'm trying to render a partial, but it's not using my @user_name variable. When you render a partial in a controller, do you need to do something special to pass in variables?

Looking at the Rails guides, I didn't see anything that said @instance_variables wouldn't be available in a partial.

Here is my user#new controller:

  def new
    if signed_in?
      redirect_to current_user
    else
      @user = User.new
    end

    # Used to show "log in" instead of "sign up" on render. Set in URL request.
    if params[:show_log_in] == true
      @show_log_in = true; //???? doesn't seem to get passed into partial.
    end

    respond_to do |format|
      format.html {}
      # JS is used for modal windows when this is accessed asynchronously.
      # e.g. a button is clicked that requires user to be signed in.
      format.js { render "shared/_signup_modal.html.erb" } //???? @show_log_in doesnt seem to get passed in?
    end
  end
Was it helpful?

Solution 2

Instance variables defined in controller would be available in views, including partial. There is no doubt. But the problem is not here.

The problem is about params. params values are all in String. So, the evaluation if params[:show_log_in] == true is wrong and always returns false, and the instance defined there will never be sent.

You need to compare it as a string.

if params[:show_log_in] == "true"

Moreover, it is not good you render a HTML partial in a JS response. I'm not sure if this will work but the legit way is to render js.erb file.

OTHER TIPS

You need to pass the variable. In your respond_to block, you'll want format.js {@show_log_in}. I typically use respond_to and respond_with though. It's prettier.

Then, you'll have to make an adjustment in your view.

new.js.erb

$('#selector').html("<%= j render partial: 'shared/_signup_modal' %>");

The partial you're rendering there will have access to the @variables you pass it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top