0

레일 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_idpreparation_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 } 

왜 이것은 단지 하나 개의 매개 변수를 사용하여 발생합니까? 내가 놓친 게 뭔가 있니? 그것은 레일에있는 버그입니까?

답변

1

preparation_time 열의 유형을 변경해야합니다. 당신과 같이이를 수 있습니다

class ChangePreparationTimeColumn < ActiveRecord::Migration 

    def change 
    #change preparation time columntype from time to integer 
    change_column :recipes, :preparation_time, :integer 
    end 
end 

어떤 이유로 시간으로 유형을 유지하지만, 매개 변수를 확인하고 싶다면

먼저 당신은 항상 할 수있는 변환됩니다 : 생성 된 마이그레이션에 그런

rails generate migration change_preparation_time_column 

모델에서 다음과 같습니다. (이전에 수행하는 것이 좋습니다.)

Class Recipe 
    ... 

    before_save :convert_prep_time 

    def convert_prep_time 
     self.preparation_time = self.preparation_time.to_i unless self.preparation_time.blank? 
    end 

end 
+0

그렇습니다. prepare_time은 허용되었지만 문자열 인 경우에만 prepare_time을 거부하는 이유는 무엇입니까? – ehp

+0

아, 죄송합니다. 질문을 잘못 읽으십시오. 나는 이것을 약간 생각할 것이다. – Jay

+0

preparation_time에 대한 귀하의 요리법 테이블에 어떤 유형의 컬럼을 사용하고 있습니까? 문자열로 설정하면 Rails는 자동으로 정수로 변환되지 않습니다. – Jay

관련 문제