chell
chell

Reputation: 7866

Why is my log showing a partial rendered twice Rails

I want to show an easier example of the same thing:

Started GET "/greetings/new" for 127.0.0.1 at 2011-09-29 15:30:46 +0700
  Processing by GreetingsController#new as JS
  Board Load (0.6ms)  SELECT "boards".* FROM "boards" WHERE "boards"."id" = 12 LIMIT 1
  User Load (0.9ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
  Upload Load (0.2ms)  SELECT "uploads".* FROM "uploads" WHERE ("uploads".uploadable_id = 1 AND "uploads".uploadable_type = 'User') LIMIT 1
Rendered greetings/_greeting_form.html.erb (108.9ms)
Rendered greetings/_greeting_form.html.erb (4.1ms)
Rendered greetings/new.js.erb (116.9ms)
Completed 200 OK in 302ms (Views: 126.5ms | ActiveRecord: 1.7ms)

The log shows that the _greeting_form.html.erb is being rendered twice. The partial is rendered with an Ajax call to the controller.

Controller:

 def new
    @greeting = Greeting.new
    @user = current_user || User.new
    respond_to do |format|
      format.js {render :action => 'new'}
    end
  end

new.js.erb

    if($('#boxGreeting').length == 0){
$('#buttons').after($(" <%=escape_javascript(render 'greeting_form', :user => @user, :greeting => @greeting) %>").fadeIn('fast'));      

            }
            else
            {
            $('#boxGreeting').replaceWith("<%=escape_javascript(render 'greeting_form', :user =>@user, :greeting => @greeting)%>");
            }

Upvotes: 2

Views: 1332

Answers (1)

arnep
arnep

Reputation: 6241

You are calling render 'greeting_form' twice in your new.js.erb. If you look into the output .js file in your browser you will see that the partial appears twice.

The browser will later evaluate your javascript if-clause and use either the first or the second of the pre-rendered "greeting_form" partials.

You can avoid parsing it twice by assigning the render result to a variable and then use this variable within the if or else part:

var greeting_form = " <%=escape_javascript(render 'greeting_form', :user => @user, :greeting => @greeting) %>";
if($('#boxGreeting').length == 0) {
    $('#buttons').after($(greeting_form).fadeIn('fast'));      
}
else {
    $('#boxGreeting').replaceWith(greeting_form);
}

Upvotes: 2

Related Questions