我正在关注RoR 3 Rails教程,但是为了升级到更新版本,我使用Rails 3.1代替3.0.11进行了不同的堆栈。
我阅读了发行说明并发现了资产管道和其他改进。 我还注意到jQuery现在是包含的默认javascript框架(以前是原型框架)。
不幸的是我无法找到我的问题的任何答案。
使用Rails 3.1没有Ajax调用正常工作吗?
提交行动时,我们假设:
不幸的是,pt 2无效。生成请求并正确完成操作(db已更新),但页面永远不会更新。
我猜这是与javascript lib或不合适的javascript erb更新代码相关的事情。
以下是html erb视图代码
<%= form_for current_user.relationships.build(:followed_id => @user.id),
:remote => true do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<div class="actions"><%= f.submit "Follow" %></div>
<% end %>
和我的js erb代码,它应该在提交Ajax请求后更新div
$("follow_form").update("<%= escape_javascript(render('users/unfollow')) %>")
$("followers").update('<%= "#{@user.followers.count} followers" %>')
控制器操作如下
def create
@user = User.find(params[:relationship][:followed_id])
current_user.follow!(@user)
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end
检查网络服务器的日志文件我可以轻松找到js erb调用和呈现的行
Started POST "/relationships" for 127.0.0.1 at 2012-01-20 10:12:51 +0100
Processing by RelationshipsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"htCzq+KZUkwVfLZmSx48OR5sSphQTE0rs0fFiX1ZJbg=", "relationship"=>{"followed_id"=>"6"}, "commit"=>"Follow"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", "6"]]
(0.2ms) BEGIN
SQL (104.1ms) INSERT INTO "relationships" ("created_at", "followed_id", "follower_id", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Fri, 20 Jan 2012 09:12:51 UTC +00:00], ["followed_id", 6], ["follower_id", 1], ["updated_at", Fri, 20 Jan 2012 09:12:51 UTC +00:00]]
(0.9ms) COMMIT
Relationship Load (0.6ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."follower_id" = 1 AND "relationships"."followed_id" = 6 LIMIT 1
Rendered users/_unfollow.html.erb (4.1ms)
(0.8ms) SELECT COUNT(*) FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."follower_id" WHERE "relationships"."followed_id" = 6
Rendered relationships/create.js.erb (9.2ms)
Completed 200 OK in 251ms (Views: 51.9ms | ActiveRecord: 115.4ms)
不幸的是,div没有得到更新。我经历了很多答案(在dev中清空public / asset文件夹,检查asset / application.rb以确保包含jquery,...)但是我的想法用完了。我应该在哪里了解这个问题的根本原因?有人在从Rails 3.0.11迁移到Rails 3.1时遇到过这种情况吗?
此致/ J。
答案 0 :(得分:0)
好吧,我不是大jquery向导,但是我将它用于类似目的:
$("#cart_container").replaceWith("<%= escape_javascript(render(:partial => 'portal/carts/cart_container')) %>");
或(如果所有具有特定类别的项目都要替换)
$('.carts').replaceWith("<%= escape_javascript(render(:partial => 'portal/carts/carts_table', :locals => {:carts => @carts})) %>")
$('.active_cart').effect("highlight", {color: '#00aa00'}, 500);
因此jQuery和prototype之间的主要区别似乎是使用replaceWith 并且$ function需要#作为项目ID或。找到课程。
所以你的代码看起来应该是这样的:
$("#follow_form").replaceWith("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").replaceWith('<%= "#{@user.followers.count} followers" %>')