2011-05-06 36 views
1

我正在使用rialscasts#74作爲指導。Rails3與jQuery的動態表單字段

我想通過文本鏈接動態添加表單域。在railscast情節他實現它非常漂亮,使用下面的代碼:projects_help.rb內

<!-- layouts/application.rhtml --> 
<%= javascript_include_tag :defaults %> 

<!-- projects/new.rhtml --> 
<div id="tasks"> 
    <%= render :partial => 'task', :collection => @project.tasks %> 
</div> 
<p><%= add_task_link "Add a task" %></p> 

<!-- projects/_task.rhtml --> 
<div class="task"> 
<% fields_for "project[task_attributes][]", task do |task_form| %> 
    <p> 
    Task: <%= task_form.text_field :name %> 
    <%= link_to_function "remove", "$(this).up('.task').remove()" %> 
    </p> 
<% end %> 
</div> 

# projects_helper.rb 

def add_task_link(name) 
    link_to_function name do |page| 
     page.insert_html :bottom, :tasks, :partial => 'task', :object => Task.new 
    end 
end 

內容是什麼,我最感興趣的問題是,他通過樣機這樣做。我正在尋找一個確切的重複實現使用jQuery(和rails3)。你怎麼看?謝謝!

回答

12

雅我想說的 - 這是一個非常古老的railscast,並且使用了過時的做法和舊的框架。我會盡力幫助你。

佈局/ application.erb

<%= javascript_include_tag :defaults %> 

項目/ new.erb

<div id="tasks"> 
    <%= render :partial => 'task', :collection => @project.tasks %> 
</div> 
<p><%= add_task_link "Add a task" %></p> 

項目/ _task.erb

<div class="task"> 
<!-- I think this part should still work --> 
<%= fields_for "project[task_attributes][]", task do |task_form| %> 
    <p> 
    Task: <%= task_form.text_field :name %> 
    <!-- We're going to be defining the click behavior with unobtrusive jQuery --> 
    <%= link_to "remove", "#", :class => 'remove_task' 
    </p> 
<% end %> 
</div> 

projects_helper.rb

def add_task_link(name) 
    # This is a trick I picked up... if you don't feel like installing a 
    # javascript templating engine, or something like Jammit, but still want 
    # to render more than very simple html using JS, you can render a partial 
    # into one of the data-attributes on the element. 
    # 
    # Using Jammit's JST abilities may be worthwhile if it's something you do 
    # frequently though. 
    link_to name, "#", "data-partial" => h(render(:partial => 'task', :object => Task.new)), :class => 'add_task' 
end 

公共/ Java腳本/ application.js中

$(function(){ 
    // Binds to the remove task link... 
    $('.remove_task').live('click', function(e){ 
    e.preventDefault(); 
    $(this).parents('.task').remove(); 
    }); 

    // Add task link, note that the content we're appending 
    // to the tasks list comes straight out of the data-partial 
    // attribute that we defined in the link itself. 
    $('.add_task').live('click', function(e){ 
    e.preventDefault(); 
    $('#tasks').append($(this).data('partial')); 
    }); 
}); 
+0

我的數據部分是未經過轉換的,並且無處不在呈現元素的渲染。有什麼我在這裏失蹤或做錯了嗎?它似乎沒有正確渲染,至少在Rails 3.1中 – 2011-08-19 08:58:01

+1

@DFischer是否確保將h()放在該屬性中的渲染周圍?我注意到,有時候這並不是出於某種原因,所以我的解決方法是這樣做:'h(render(stuff_here)+'')''。我懷疑問題是render()被標記爲html_safe,然後運行h()並且看到它的html安全,因此由於某種原因決定不轉義它。追加一個空字符串將使其不再是html_safe,所以希望工程:) – nzifnab 2011-08-24 18:49:15