Search code examples
ruby-on-railsrubyajaxruby-on-rails-3rjs

Rails Ajax single line RJS files


Everything I am reading about rails 3 and AJAX says that we should have

respond_to do |format| 
   @wines = Wine.all(:conditions => {:category => "Sparkling"})
   format.js
end

and then a seperate js.erb file that is

$("wines").update("<%=  escape_javascript(render :partial => "sparkling")%>")

but that one line js file seems a little extreme, can I do something like this:

respond_to do |format| 
   @wines = Wine.all(:conditions => {:category => "Sparkling"})
   format.js {render :js => '$("wines").update("<%=  escape_javascript(render :partial => "sparkling")%>"')}
end

and then leave out the extra .js.erb file The problem I see here is a double render (am noob so I'm not sure)? What is the best way to do this?


Solution

  • Inline RJS is a bad practice, but you can use it like this:

    def your_action 
      @wines = Wine.all(:conditions => {:category => "Sparkling"})
      respond_to do |format| 
        format.js {render :update do |page|
          page << '$("wines").update("<%=  escape_javascript(render :partial => "sparkling")%>"')
        end}
      end
    end
    

    UPD

    No, it's not silly to store one more file. It makes your controllers cleaner. Look with your_action.js.erb

    # your controller
    def your_action 
      @wines = Wine.all(:conditions => {:category => "Sparkling"})
    end
    # your you_action.js.erb
    $("wines").update("<%=  escape_javascript(render :partial => "sparkling")%>"
    

    That is two lines instead of 6 :)