2016-02-20 71 views
0

我有一個屬於並擁有許多'服務'的模型'資料'。複選框的嵌套屬性

在個人資料頁面上,用戶可以通過複選框勾選他擁有的「服務」。

目前我正在努力獲得多個複選框值來添加到'服務'例如,在我看來我有兩個複選框,如果我選中兩個複選框,只有最後一個複選框被選中添加?

我的觀點:

<h3>Please click the services you provide</h3> 

     <div class="checkbox"> 
     <label> <input type="checkbox" name="profile[services_attributes] 
[services][service_type]" value="handyman">Handyman</label> 
     </div> 

     <div class="checkbox"> 
     <label> <input type="checkbox" name="profile[services_attributes] 
[services][service_type]" value="plumber">Plumber</label> 
     </div> 

我的控制器:

def create 
@profile = Profile.new(profile_params) 

if @profile.save 

    redirect_to '/profiles' 

else 
    render '/profiles' 
    end 
    end 

    ... 

    private 

    def profile_params 
params.require(:profile).permit(:bio, london_attributes: [:id, :south, 
:north, :east, :west, :central], services_attributes:[services: 
[:service_type]]) 
    end 
end 

控制檯錯誤:

Processing by ProfilesController#create as HTML 
    Parameters: {"authenticity_token"=>"rCk4/TbBsARCN2b9aSyxsXdW1mHBiZ1GrZNsmqTjsVIsDiQ294zYMlq0JkklRFeildiOLmfM3aYA0B3Lw+Apew==", 
"profile"=>{"bio"=>"", "services_attributes"=>{"services"=>{"service_type"=>"plumber"}}}} 
    (0.1ms) begin transaction 
    SQL (0.5ms) INSERT INTO "profiles" ("bio", "created_at", "updated_at") 
VALUES (?, ?, ?) [["bio", ""], ["created_at", "2016-02-20 
15:41:22.636669"], ["updated_at", "2016-02-20 15:41:22.636669"]] 
    SQL (0.1ms) INSERT INTO "services" ("service_type", "created_at", 
"updated_at") VALUES (?, ?, ?) [["service_type", "plumber"], ["created_at", 
"2016-02-20 15:41:22.638707"], ["updated_at", "2016-02-20 15:41:22.638707"]] 
    SQL (0.1ms) INSERT INTO "profiles_services" ("profile_id", "service_id") 
VALUES (?, ?) [["profile_id", 124], ["service_id", 14]] 
+1

發佈的這不是一個錯誤?請更新 –

+0

嗨Hieu,已更新我的問題 – Stoob

回答

1

您可以重構您的視圖:

<label>Handyman</label> 
<%= check_box_tag 'profile[services_attributes] 
[services][service_type][]', 'handyman' %> 

<label>Plumber</label> 
<%= check_box_tag 'profile[services_attributes] 
[services][service_type][]', 'plumber' %> 

請注意,現在的複選框名稱是profile[services_attributes][services][service_type][]

+0

超級,讓我在路上! – Stoob