Search code examples
ruby-on-railsruby-on-rails-4renderpartial

Rails render partial does not use @instance_variable


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

Solution

  • 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.