2011-11-21 99 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文章如果我不夠清楚。