我有一个常量的'服务'模型,它有一个'id'列和一个'service_type'列。
"服务"belong_to_and_has_many"配置文件"
创建个人资料时,用户可以通过多项选择复选框选择他们提供的服务。
提交时,我想将服务添加到用户配置文件中。
目前,我通过使用服务参数中的"服务"数组的值来执行此操作,并尝试在控制器中循环数组,为数组中的每个元素值添加关联,足以说它有点混乱并且不起作用,我需要帮助尝试使其工作。
控制器:
def create
@profile = Profile.new(profile_params)
if @profile.save
add = []
types = params(:services)
types.each do |service|
p = Service.where('service_type LIKE ?', '%#{service}%')
add << p
self.services << add
end
redirect_to '/'
else
render '/profiles'
end
end
def profile_params
params.require(:profile).permit(:bio, :services, london_attributes: [:id, :south, :north, :east, :west, :central])
结束
查看: - 每个 ="name" 与"服务"模型中的"service_type"相同:
<h3>Please click the services you provide</h3>
<div class="checkbox">
<label> <input type="checkbox" name="profile[services][]" value="handyman">Handyman</label>
</div>
<div class="checkbox">
<label> <input type="checkbox" name="profile[services][]" value="plumber">Plumber</label>
</div>
带有令牌的参数删除了其他参数:
Parameters: "profile"=>{
"bio"=>"",
"services"=>
["handyman", "plumber"]}}
Unpermitted parameter: services
profile.rb:
class Profile < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :places
has_and_belongs_to_many :services
accepts_nested_attributes_for :places
accepts_nested_attributes_for :services
has_one :london
accepts_nested_attributes_for :london
不允许的参数:服务
您应该在profile_params
中将:services
更改为:service_ids => []
def profile_params
params.require(:profile).permit(:bio, :service_ids => [], london_attributes: [:id, :south, :north, :east, :west, :central])
end
并使用collection_check_boxes生成复选框。
<%= f.collection_check_boxes(:service_ids, Service.all, :id, :name) %>
同时将create
方法更改为以下内容
def create
@profile = Profile.new(profile_params)
if @profile.save
redirect_to '/'
else
render '/profiles'
end
end