Rails 4 - 不保存嵌套属性

时间:2016-02-23 18:21:41

标签: ruby ruby-on-rails-4 model nested gorm

我有这些模特:

class Company < ActiveRecord::Base
  has_many :company_services, dependent: :destroy
  has_many :services, through: :company_services
  accepts_nested_attributes_for :services, :allow_destroy => true
end
class Service < ActiveRecord::Base
  has_many :company_services
  has_many :companies, through: :company_services
end
class CompanyService < ActiveRecord::Base
  belongs_to :company
  belongs_to :service
  validates_uniqueness_of :service_id, scope: :company_id
end

然后在控制器动作中:

  def new
    @company = Company.new
    @company.services.build
  end
  def create
    ...
    @company = Company.new(company_params)
respond_to do |format|
      if @company.save
        format.html { redirect_to edit_company_path(@company), notice: 'Company was successfully created.' }
        format.json { render action: 'show', status: :created, location: @company }
      else
        format.html { render action: 'new', notice: 'Company could not be saved.' }
        format.json { render json: @company.errors, status: :unprocessable_entity }
      end
    end
  end

  private
    params.require(:company).permit(:name, :email, ..., {:service_ids => [:id, :name, :label, :icon, :service_type]}).merge(latlng: geocode)

并查看:

<%= simple_form_for @company do |f| %>
  ...
  <%= f.association :services, 
                             as: :check_boxes, 
                             label_method: :label, 
                             value_method: :id,
                             item_wrapper_class: 'manage_services',
                             label: 'Services' %>
  ...
<% end %>

正确呈现复选框,当我保存表单时,不保存服务。 我也试过了

{:service_ids => []}

在控制器的permit中,但是返回了此错误:

undefined method `name' for nil:NilClass

我昨天卡在这里仍然无法理解......我在SO上也发现了一些类似的话题,但没有一个对我有帮助。

我在这里错了什么?

提前谢谢。

修改 这是我发送表格后得到的参数列表:

  

参数:{&#34; utf8&#34; =&gt;&#34;✓&#34;,   &#34; authenticity_token&#34; = GT;&#34; igyh4EBcdXT5b3rj / Zy52Mi27dh4u81GWCtUmGNCXw4 =&#34 ;,   &#34;公司&#34; =&gt; {&#34; company_name&#34; =&gt;&#34; 0&#34;,...,&#34; service_ids&#34; =&gt; [&# 34; 2&#34;,&#34; 7&#34;,&#34; 12&#34;,   &#34; 17&#34;,&#34; 22&#34;,&#34; 27&#34;,&#34; 32&#34;,&#34;&#34;],&#34; mc_num&#34; =&gt;&#34; 3512616&#34;,&#34; dot_num&#34; =&gt;&#34; 126126&#34;,   ...},&#34;提交&#34; =&gt;&#34;更新&#34;}

0 个答案:

没有答案