2013-03-20 161 views
0

我想實現一個使用rails3中的allows_nested_attributes_for功能來實現調查表單的嵌套窗體。調查有很多問題有很多答案。隱藏字段不是從助手在rails中生成

我想通過隱藏_destroy字段,並使用jQuery來設置它,當一個鏈接被點擊。它工作正常,但當我嘗試使用輔助方法進行相同操作時,隱藏字段不顯示。

module ApplicationHelper 
    def link_to_remove_field(link_text, builder) 
    builder.hidden_field :_destroy 
    link_to link_text, '#', :class=>"remove_field" 
    end 
end 

這是我想使用的jquery函數。

$(function(){ 
    $('.remove_field').on('click', function(element){ 
    $(this).prev("input[type=hidden]").val("1"); 
    $(this).parent('.field').hide(); 
    return false; 
    }); 
}); 

這是部分從我打電話助手

<%= f.label :question %><br /> 
<%= f.text_area :question, :rows=>1 %> 
<%= link_to_remove_field("Remove question", f) %> 

的標籤出現,但隱藏字段不顯示。

<textarea cols="40" id="old_question_set_old_questions_attributes_2_question" name="old_question_set[old_questions_attributes][2][question]" rows="1"></textarea> 
<a href="#" class="remove_field">Remove question</a> 

回答

1

link_to_remove_field只返回最後一行也就是link_to因爲你忘了加上hidden_field。改變你的幫手

def link_to_remove_field(link_text, builder) 
    builder.hidden_field(:_destroy) + 
    link_to(link_text, '#', :class => "remove_field") 
end 

請注意調用此方法

link_to_remove_field(....).html_safe 
+0

當我把括號問題得到固定時,你可能需要調用html_safe:_destroy和的link_to。 不是沒有括號的紅寶石應該工作嗎? 我是一個紅寶石小白。爲什麼你必須在助手的每行之後添加'+'符號? – punitjajodia 2013-03-20 07:18:18