Oscar Sidebo
Oscar Sidebo

Reputation: 65

Controller not rendering show.js.haml during AJAX

I'm making a simple AJAX call from a from_tag (search box) and want to show the results without refreshing page. The issue is that even though I can see in server console that the show action is being processed as JS, it still renders the HTML and not the js.haml file. The only way I'm getting controller to render js is by changing name to show.js . It then works as it should. show.js.erb doesn't work either. I've also tried format.js {render layout: false} without any luck. It seem to be an problem on the controller side but I might be wrong here. Any ideas appreciated!

Edit:

The controller action is working using the render "show.js.haml" option. The other issue is that escape_javascript doesn't do anything in below js.haml file.

show.js.haml

$("#main").html("#{escape_javascript(render 'artists/show', locals: {artist: @artist, updates, @updates, reach: @reach, reach_diff: @reach_diff})}");   

controller

class ArtistsController < ApplicationController

        def index
            if params[:search]
                @artist=Artist.find_by(name: params[:search])
                redirect_to action: "show", id: @artist.id
            else
                @artists= Artist.all
            end
        end

        def show
            @artist= Artist.find(params[:id])
            @updates = @artist.updates.order(created_at: :desc)
            @reach = @artist.reachupdates.order(created_at: :desc)
            @reach_diff= Reachupdate.last_week_diff(@artist.id)

            respond_to do |format|
                format.html
                format.js {render "show.js.haml", layout: false}
            end
        end
    end

Upvotes: 0

Views: 802

Answers (1)

Pavan
Pavan

Reputation: 33542

You need to change render layout: false to render 'show.js.haml', layout: false

def show
  @artist= Artist.find(params[:id])
  @updates = @artist.updates.order(created_at: :desc)
  @reach = @artist.reachupdates.order(created_at: :desc)
  @reach_diff= Reachupdate.last_week_diff(@artist.id)

  respond_to do |format|
    format.html
    format.js {render 'show.js.haml', layout: false}
  end
end

Update:

The next issue I'm having is to insert ruby objects to the js file

If the file 'articles/show' is a partial file then the problem is the locals keyword should be used along with partial keyword in order to work. Try changing this

$("#main").html("#{escape_javascript(render 'artists/show', locals: {artist: @artist, updates, @updates, reach: @reach, reach_diff: @reach_diff})}");

to

$("#main").html("#{escape_javascript(render partial: 'artists/show', locals: {artist: @artist, updates, @updates, reach: @reach, reach_diff: @reach_diff})}");

Or

Just remove locals

$("#main").html("#{escape_javascript(render 'artists/show', artist: @artist, updates, @updates, reach: @reach, reach_diff: @reach_diff)}");

Upvotes: 1

Related Questions