我想展示一个更简单的例子:
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)
日志显示_greeting_form.html.erb正在呈现两次。部分是通过对控制器的Ajax调用来呈现的。
控制器:
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)%>");
}
答案 0 :(得分:2)
您在render 'greeting_form'
中两次致电new.js.erb
。如果您在浏览器中查看输出.js文件,您将看到部分出现两次。
浏览器稍后将评估您的javascript if子句,并使用预渲染的“greeting_form”部分的第一个或第二个。
您可以通过将渲染结果赋值给变量来避免解析它,然后在if或else部分中使用此变量:
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);
}