2013-06-02 21 views
2

我的Rails應用程序3.2.13使用複選框數組(相同的字段名稱多種可能的值)的工作,用標籤:軌怎麼弄label_tag當多個(陣列)check_box_tag

%table 
    %tr 
    %td 
     = check_box_tag 'fruits[]', 'apple' 
    %td 
     = label_tag 'fruits[apple]', 'I like Apples' 
    %tr 
    %td 
     = check_box_tag 'fruits[]', 'banana' 
    %td 
     = label_tag 'fruits[banana]', 'I like Bananas' 

形式正確提交複選框在參數params [:水果] => ['蘋果','香蕉']

但標籤被打破 - 點擊標籤什麼都不做。 (因爲html標籤標籤的='fruits_xxxx',但所有複選框的ID只是id ='fruits_',所以標籤不會與複選框相關聯。)

如何在這種情況下指定label_tag它與check_box_tag正確關聯的方式是什麼? (我也嘗試使用標籤標籤的a:值,例如= label_tag 'fruits[]', I like Apples', :value => 'apple',但這也不起作用)

注意:我最近使用的是標籤標籤的塊格式(將複選框放在標籤內)下面的標籤的作品,但是,使用塊結構防止把複選框和標籤在單獨的細胞:

= label_tag do 
    = check_box_tag 'fruits[]', 'apple' 
    I like Apples 
= label_tag do 
    = check_box_tag 'fruits[]', 'banana' 
    I like Bananas 

回答

5

可以傳遞複選框屬性check_box_tag方法第四個參數。在這種情況下,您需要將id設置爲等於標籤的「for」屬性。

%td 
    = check_box_tag 'fruits[]', 'apple', params[:fruits] && params[:fruits].include?('apple'), :id => 'fruits_apple' 
%td 
    = label_tag 'fruits_apple', 'I like Apples' 
+0

啊,是的,完美的,謝謝! – jpwynn

1

如果有人跑到這裏通過google搜索這裏有一個更正確的答案,如果你使用的是form_for

%td 
    = f.check_box :fruits, { multiple: true }, 'apple' 
%td 
    = f.label :fruits, 'I like Apples', value: 'apple' 
+0

這工作得很好。謝謝。 –