【问题标题】:Mongoid embedded documents and Rails strong parameters not workingMongoid 嵌入文档和 Rails 强参数不起作用
【发布时间】:2014-10-10 01:44:06
【问题描述】:

我在 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!

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

【问题讨论】:

    标签: json angularjs http json-api


    【解决方案1】:

    你必须接受nested_attributes的分配

     class Company
      include Mongoid::Document
    
      field :name, type: String
      embeds_many :people, class_name: 'Person'
      accepts_nested_attributes_for :people
    end
    

    【讨论】:

    • 无效。当他们点击更新方法时,参数已经有这个问题了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2015-04-23
    相关资源
    最近更新 更多