我无法保存模特。
公司模型:文件模型= 1:N
使用JSON,我想知道cyaan获得文档的参数。 但我不明白。 它能理解哪里不好吗? 请告诉我。
发布数据
{
"name": "name",
"address": "asd",
"phone": "0394564",
"fax": "168465",
"mail": "mailtest",
"documents":[{
"name": "name",
"address": "asd",
"phone": "58465",
"fax": "543543"
},{
"name": "test",
"address": "asd",
"phone": "5452452",
"fax": "24534535"
}]
}
代码 [模型] company.rb
class Company < ActiveRecord::Base
has_many :documents
accepts_nested_attributes_for :documents
end
[模型] document.rb
class Document < ActiveRecord::Base
belongs_to :company
end
[控制器] company_controller.rb
def create
@company = Company.new(company_params)
if @company.save
render json: @company, status: :created
else
render json: @company.errors, status: :unprocessable_entity
end
end
def company_params
params.require(:company).permit(:name, :address, :phone, :fax, :mail, documents_attributes: [:name])
end
LOG示例
Started POST "/api/v1/companies/" for 192.168.1.19 at 2014-06-04 21:32:46 +0900
Processing by Api::V1::CompaniesController#create as JSON
Parameters: {"name"=>"name", "address"=>"asd", "phone"=>"12345", "fax"=>"12345", "mail"=>"mailtest", "documents"=>[{"name"=>"name", "address"=>"asd", "phone"=>"12345", "fax"=>"12345"}, {"name"=>"name", "address"=>"asd", "phone"=>"12345", "fax"=>"12345"}], "company"=>{"name"=>"name", "address"=>"asd", "phone"=>"12345", "fax"=>"12345", "mail"=>"mailtest"}}
(0.1ms) begin transaction
SQL (1.8ms) INSERT INTO "companies" ("address", "created_at", "fax", "mail", "name", "phone", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["address", "asd"], ["created_at", "2014-06-04 12:32:46.583770"], ["fax", "12345"], ["mail", "mailtest"], ["name", "name"], ["phone", "12345"], ["updated_at", "2014-06-04 12:32:46.583770"]]
(3.8ms) commit transaction
答案 0 :(得分:1)
只要您在强对手中要求对象,就必须声明对象。
{"company"=>{"name"=>...}}
Rails将捕获“公司”值并允许它们。
这里有同样的问题:
Why isn't my Rails API saving anything to the database?
编辑:
在你的参数中:
..
"documents":[{
..
在许可证中:
documents_attributes:
也许这就是原因。
相关信息:
http://robots.thoughtbot.com/accepts-nested-attributes-for-with-has-many-through