如何在不重新加载页面的情况下更改ActiveRecord值后更新'div'内容?

时间:2011-01-13 01:16:21

标签: ruby-on-rails ajax activerecord prototypejs scriptaculous

我正在使用带有Prototype / Scriptaculous的Ruby on Rails 3,我试图在ActiveRecord值更改后更新'div'内容,而不重新加载页面。

在“edit.html.erb”中我有:

...

<div id="test_id">
  <%= @account.name.to_s %>
</div>

<%= link_to_function( "Make test" ) do |page|
  page.replace_html :test_id, @account.name.to_s
end %>

...

在点击“Make test”之前,我更新了'@ account.name'值,即使是通过AJAX也是如此。然后,单击“进行测试”,模板不会更改。

以下是步骤:

  1. 我显示页面
  2. 我通过AJAX更新'@ account.name'
  3. 我点击“制作测试”
  4. 'div'与'id =“test_id”'不会改变!
  5. 我做错了什么?

    P.S。:我认为@account不会在页面中重新加载,也不会在数据库中更改其值。如果是这样,我该怎么办?


    我已经看过Railscasts“AJAX with RJS”,我跟着一个例子(就像我的那样),但它对我不起作用。

1 个答案:

答案 0 :(得分:1)

如果您在@ account.name的值为“George”时呈现了edit.html.erb,则HTML将保持不变(值为“George”),直到您刷新它为止。您对link_to_function的调用是在页面加载时,呈现一个调用javascript的html链接,用“George”替换“test_id”div的内部html。除非您替换该HTML,否则它将始终用'George'替换该div的内部html。

如果不确切知道自己想做什么,很难推荐解决方案......

已更新以获得更多详细信息:

如果您正在进行AJAX调用,将服务器上帐户名的值更改为“Fred”,并希望该更改显示在页面上,则应刷新使用该值的页面部分相同的AJAX调用(相同的控制器操作)。

您的link_to_function会生成这样的HTML(如果在呈现页面时@ account.name为'George'):

<a onclick="try { Element.update("test_id", "George"); ... >Make test</a>

它不是一个ajax调用,它只是一个执行javascript的链接。如果你想让它成为ajax调用,找到帐户名的最新值并刷新test_id div,请执行以下操作:

<%# you need prototype included, but it should probably be in application.rhtml %> 
<%= javascript_include_tag "prototype.js" %>

<div id="test_id">
  <%= @account.name.to_s %>
</div>

<%= link_to_remote "Make test", :url => { :controller => "account", :action => "change_name" } %>

'Make test'链接现在将对'account'控制器中的'change_name'方法执行AJAX调用。这个方法看起来像这样:

def change_name
  # here you would load the account from the db; I'm cheating
  @account = Account.new(:name => "Fred")

  render :update do |page|
    page.replace_html :test_id, :text => @account.name.to_s
  end
end