2011-11-21 97 views
1

我确定这个问题已经在不同的上下文中被问到过了,但我还是很想搞清楚AJAX Rails,我猜,一般的Rails(有点让我想知道如果我应该回到PHP ...)。好吧,无论如何,我有这个表单,我想要AJAXify。Ruby on Rails的AJAX表单问题

这是 “清单” 视图这是 “主题” 控制器

<h1>Listing Subjects</h1> 

<ul id="subject_list"> 

    <% @subjects.each do |c| %> 
    <li><%= link_to c.name, :action => 'show', :id => c.id %></li> 
    <% end %> 

</ul> 

<p id="add_link"><%= link_to_function("Add a Subject", 
"Element.remove('add_link'); Element.show('add_subject')")%></p> 

<div id="add_subject" style="display:none;"> 

<%= form_tag(:action => 'create') do%> 
    Name: <%= text_field "subject", "name" %> 
    <%= submit_tag 'Add' %> 
<% end %> 

</div> 

代码为我的 “主题” 控制器

class SubjectController < ApplicationController 

    def list 
    @subjects = User.find(:all) 
    end 

    def show 
    @subject = User.find(params[:id]) 
    end 

    def create 
    @subject = User.new(params[:subject]) 
    if @subject.save 
     render :partial => 'subject', :object => @subject 
    end 
    end 

end 

我的 “主题” 部分的一部分

<li id="subject_<%= subject.id %>"> 
<%= link_to subject.name, :action => 'show', :id => subject.id %> 
</li> 

而用户只是一个简单的模型,我做了包含两列“名称”和“电子邮件”。

此代码当前的工作原理是当您单击“添加”时,显示文本字段输入。在输入内容中输入内容并提交时,“_show”部分将显示在创建链接中。我正在关注Rails 2.0教程,但我有3.0,我已阅读了一些教程,他们都提到“:remote => true”和jquery_ujs.js,但我不知道如何将它们应用于“form_tag”,而不是“form_for”Rails助手。

基本上我想异步地将元素添加到列表底部而无需页面加载。我真的很努力去理解所有我能找到的教程,但我无法弄清楚。

回答

0

我相信你最好使用一些Unobtrusive JavaScript来告诉你的应用程序 和浏览器你想要渲染什么以及如何渲染。 你想从简单的render :partial => 'subject', :object => @subject代码中得到太多。

这是我的代码片段,可能对您有所帮助。

# in the view (:remote => true for form_tag is not problem at all) 
<%= form_tag({:controller => :products, :action => :empty_cart }, {:id => 'empty_cart', :remote => true}) do %> 
    <%= submit_tag 'Clear' %> 
<% end %> 

# in the controller (note that format.js section in the respond_to block) 
def empty_cart 
    ... 
    respond_to do |format| 
    format.html { redirect_to :root, :notice => 'Your cart is empty now' } # in the case of disabled JS support 
    format.js { render :js => "$('#empty_cart').fadeOut()" } # or you can place js code in the empty_cart.js.erb file and specify format.js here without the block 
    end 
end 

检查this文章如果我不够清楚。