3

我在 Mongoid/Rails 中有一个 1-N 关系:

class Company
  include Mongoid::Document

  field :name, type: String
  embeds_many :people, class_name: 'Person'
end

class Person
  include Mongoid::Document

  field :first_name, type: String
  embedded_in :company, class_name: 'Company', inverse_of: 'people'
end

现在我可以在控制台中成功创建公司,如下所示;例如:

> c = Company.new(name: 'GLG', :people => [{first_name: 'Jake'}])  # OK!
> c.people                                                         # OK!

然后我有一个 JSON API 控制器来更新公司,大致如下:

# PUT /api/companies/:id
def update
  if Company.update(company_params)
    # ... render JSON
  else
    # ... render error
  end
end

private

def company_params
  params.require(:company).permit(:name, :people => [:first_name])
end

现在,当 PUT 请求从前端进来时,company_params 总是缺少 :people 属性。Rails 日志说:

Parameters: {"id"=>"5436fbc64a616b5240050000", "name"=>"GLG", "people"=>[{"first_name"=>"Jake"}], "company"=>{"name"=>"GLG"}}

我没有收到“未经允许的参数”警告。我已经尝试了所有可以想到的允许人员字段的方法,但它仍然没有被包括在内。

params.require(:company).permit!

结果相同。我究竟做错了什么?

4

1 回答 1

0

您必须在分配时接受nested_attributes

 class Company
  include Mongoid::Document

  field :name, type: String
  embeds_many :people, class_name: 'Person'
  accepts_nested_attributes_for :people
end
于 2014-10-10T07:44:38.683 回答