Rails : acting weird : why layout is rendered when format.js

I don’t know why I am getting this issue. I have set remote: true in link_to helper method in view. and the controller is supposed to look like

class ProfilesController < ApplicationController
  def index
  end

  def profile_setting
    respond_to do |format|
      format.js
    end
  end
end

I have the file views/profiles/profile_setting.js.erb. I can even pry into the .js template using binding.pry [using pry-rails gem]. It renders the template but also renders layout i.e. layouts/application.html.erb

Solution:

format.js { render layout: false }

I needed to make rails not to render layout explicitly.

Reason:

After doing some research I got the answer. You might or might not have noticed that this type of mime-type conflicting issues occur only when you have named your application layout file like application.erb or application.haml or application.slim.

Did you notice anything common?

Yes, if request’s MIME type is html then Rails tries to find application.html.erb layout and yield the template it renders into it. [ layout is set true by default ].

As you predicted for js request, it searches for application.js.erb layout and yields the template.js.erb into it. Same form xml requests.

If application.js.erb is not found, it only tries to match the name application in layouts directory. So it renders application.slim or application.haml , etc.

How to fix without having to set layout: false everytime?

You can rename the application.slim or application.haml to application.html.slim. By doing this, the layout is explicitly set for html MIME type and will not be used for .js type.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s