I Can't save model.
Company Model : Document Model = 1:N
Use a JSON, I wonder cyaan get params of Documents. But I don't get it. Does it understand where is bad? Please let me know.
Post Data
{
"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"
}]
}
Code [Model]company.rb
class Company < ActiveRecord::Base
has_many :documents
accepts_nested_attributes_for :documents
end
[Model]document.rb
class Document < ActiveRecord::Base
belongs_to :company
end
[Controller]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 example
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
POST Data
section, the nested attributes appear to be under thepetshops
field. In your strong parameters declaration, they are calleddocuments_attributes
, and in your log, they appear to be justdocuments
. This is probably (the beginning of) your problem. These should all bedocuments_attributes
.