chourobin
chourobin

Reputation: 4114

Rails: rendering the js.erb template using the controller

I have a rails app trying to incorporate some AJAX where clicking new opens a modal window and a form. I want to be able to display the validation errors if it fails so in my create action, i thought about re-rendering the new.js.erb file. Is this the right approach?

def create
    @place = Place.new(params[:place])
    if @place.save
       redirect_to places_path, :notice => "Successfully created place"
    else
       render "new.js.erb"
    end
end

The result I get is escaped js text in my browser like:

$("#new_grouping").html("<div class=\"modal-header\">\n  <a class=\"close\" data-   dismiss=\"modal\">×<\/a>\n  <h3>Create a new menu section<\/h3>\n<\/div>\n<form accept-charset=\"UTF-8\" action=\"/places/1-mama-s-pizza/groupings\" class=\"simple_form new_grouping\" id=\"new_grouping\" method=\"post\" novalidate=\"novalidate\">

I've tried putting various options into the render block but no luck. Any tips?

Upvotes: 3

Views: 37066

Answers (2)

ibylich
ibylich

Reputation: 658

As i know, rendering partial in controller is a bad idea, because then response can be without content-type and some browsers can't understand this. if it is some file attached to action you should write

render :action => "create"

or if you need just render a singe partial then in your action file write

<%= render :partial => "path/to/partial" %>

as i said, then you won't have problems with content-type in response

Upvotes: 1

Vapire
Vapire

Reputation: 4578

The best practice would be to support both, AJAX and Non-AJAX calls, in case the user has javascript turned off for any reason.

def create
  @place = Place.new(params[:place])

  respond_to do |format|
    if @place.save
      format.html { redirect_to places_path, :notice => "Successfully created place" }
      format.js   # renders create.js.erb, which could be used to redirect via javascript
    else
      format.html { render :action => 'new' }
      format.js { render :action => 'new' }
    end
  end
end

The render :action => 'new' actually renders the template of the controller action new which results to new.html.erb respectively to new.js.erb depending if it's a non-AJAX or an AJAX call.

In new.js.erb goes your ERB/javascript code:

$("#new_grouping").html("<%= escape_javascript(...) %>">

Upvotes: 16

Related Questions