复选框的嵌套属性

时间:2016-02-20 15:53:22

标签: ruby-on-rails

我有一个属于'并且有许多'服务'的模型'个人资料'。

在个人资料页面上,用户可以通过复选框勾选他所拥有的“服务”。

目前我正在努力获得多个复选框值以添加到“服务”中。例如,在我的视图中,我有两个复选框,如果我选中两个复选框,则仅选中最后一个复选框?< / p>

我的观点:

<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 :(得分: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][]