레일 4.1.4 응용 프로그램에서 일부 매개 변수는 모델에 따라 처리되지 않으며 아마도 해당 유형에 따라 다를 수 있습니다. 다음과 같은 POST 요청을 할 때, 모든 매개 변수가 올바르게 처리 얻을 새로운 레시피 장소에서 올바른 값을 데이터베이스에 저장됩니다rails : 활성 레코드에서 문자열 매개 변수가 무시됩니다.
preparation_time
의 값은 정수와로 전달됩니다
POST /api/v0/recipes HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: f49d43b3-9007-9687-a24f-92e7e7c873bd
{"recipe":{"name":"Spaghetti Carbonara","description":"Catchy description", "body":"Steps here","preparation_time":200,"category_id":"1","ingredients_attributes":[{"food_id":2,"quantity":100,"unit":"g"}, {"food_id":2,"quantity":150,"unit":"g"}]}}
공지 것을 category_id
값은 문자열로 전달됩니다. 그러나 준비 시간 값이 category_id
과 같이 문자열로 전달되면 유효성 검사가 실패하여 모델 유효성 검사 규칙에 따라 preparation_time
이 필요하다는 메시지가 표시됩니다. 여기
POST /api/v0/recipes HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 70500362-9573-8684-bdaf-8dd0a0b3b05d
{"recipe":{"name":"Spaghetti Carbonara","description":"Catchy description", "body":"Steps here","preparation_time":"200","category_id":"1","ingredients_attributes":[{"food_id":2,"quantity":100,"unit":"g"}, {"food_id":2,"quantity":150,"unit":"g"}]}}
그리고 여기 preparation_time
매개 변수가 제대로 도착 있음을 보여줍니다 요청에 대한 로그입니다 :
Started POST "/api/v0/recipes" for 10.0.2.2 at 2014-07-20 17:11:08 +0200
Processing by Api::V0::RecipesController#create as */*
Parameters: {"recipe"=>{"name"=>"Spaghetti Carbonara 2", "description"=>"Catchy description", "body"=>"Steps here", "preparation_time"=>"200", "category_id"=>"1", "ingredients_attributes"=>[{"food_id"=>2, "quantity"=>100, "unit"=>"g"}, {"food_id"=>2, "quantity"=>150, "unit"=>"g"}]}}
(0.2ms) begin transaction
Food Load (1.3ms) SELECT "foods".* FROM "foods" WHERE "foods"."id" = ? LIMIT 1 [["id", 2]]
CACHE (0.0ms) SELECT "foods".* FROM "foods" WHERE "foods"."id" = ? LIMIT 1 [["id", 2]]
Recipe Exists (0.4ms) SELECT 1 AS one FROM "recipes" WHERE "recipes"."name" = 'Spaghetti Carbonara 2' LIMIT 1
(0.2ms) rollback transaction
Completed 422 Unprocessable Entity in 44ms (Views: 0.3ms | ActiveRecord: 2.1ms)
응답이 없다는 오류 메시지가 포함 preparation_time
매개 변수가 설정되지 않았습니다.
{"preparation_time":["can't be blank","is not a number"]}
상태는 422 Unprocessable Entity
입니다. category_id
및 preparation_time
장소에서
유효성 검사 규칙은 정확히 동일합니다
validates :preparation_time, presence: true, numericality: { only_integer: true, greater_than: 0 }
validates :category_id, presence: true, numericality: { only_integer: true, greater_than: 0 }
왜 이것은 단지 하나 개의 매개 변수를 사용하여 발생합니까? 내가 놓친 게 뭔가 있니? 그것은 레일에있는 버그입니까?
그렇습니다. prepare_time은 허용되었지만 문자열 인 경우에만 prepare_time을 거부하는 이유는 무엇입니까? – ehp
아, 죄송합니다. 질문을 잘못 읽으십시오. 나는 이것을 약간 생각할 것이다. – Jay
preparation_time에 대한 귀하의 요리법 테이블에 어떤 유형의 컬럼을 사용하고 있습니까? 문자열로 설정하면 Rails는 자동으로 정수로 변환되지 않습니다. – Jay