如何在Rails 4中使用has_many更新关系?

时间:2014-06-06 11:01:47

标签: ruby-on-rails

控制器有以下代码:

def create
    @employee = business.beauty_salon_employees.build(employee_params)
    if @employee.save
                #
    else
        render 'new'
    end
end

def edit
    @employee = business.beauty_salon_employees.find(params[:id])
end

def update
    @employee = business.beauty_salon_employees.find(params[:id])
    if @employee.update(employee_params)
              #
    else
        render 'edit'
    end
end

protected
    def employee_params
    params.require(:beauty_salon_employee).permit(:name, :description, :phone, { beauty_salon_service_ids: [] })
end

以下代码:

- @business.beauty_salon_services.each do |s|
    .row
        = check_box_tag "beauty_salon_employee[beauty_salon_service_ids][]", s.id, @employee.beauty_salon_services.include?(s)
        = s.name  

模型代码:

has_many :beauty_salon_employee_services, dependent: :destroy
has_many :beauty_salon_services,                    through: :beauty_salon_employee_services
accepts_nested_attributes_for :beauty_salon_services

并且

has_many :beauty_salon_employee_services, dependent: :destroy
has_many :beauty_salon_employees,             through: :beauty_salon_employee_services

问题是以下的事情:当我创建一些BeautySalonEmployee并且选中了一些复选框计数(例如,1)时,一切都很好。但是当我尝试更新此记录时没有选中复选框我没有错误,但没有更新,即当我再次打开此记录时,我仍然看到1复选框已选中。我该如何解决?怎么了?

1 个答案:

答案 0 :(得分:2)

如果未选中复选框,则不会发送。

只需添加一个名为nil的隐藏字段,例如

= hidden_field_tag 'beauty_salon_employee[beauty_salon_service_ids][]', nil

如果未选中任何复选框,则会发送此选项,但如果是,则会发送它们