Rails 4-강력한 매개 변수-중첩 된 객체
꽤 간단한 질문이 있습니다. 그러나 지금까지 해결책을 찾지 못했습니다.
서버에 보내는 JSON 문자열은 다음과 같습니다.
{
"name" : "abc",
"groundtruth" : {
"type" : "Point",
"coordinates" : [ 2.4, 6 ]
}
}
새로운 허가 방법을 사용하여 다음을 얻었습니다.
params.require(:measurement).permit(:name, :groundtruth)
이로 인해 오류가 발생하지 않지만 작성된 데이터베이스 항목에는 null
기본 값 대신 포함 됩니다.
방금 설정 한 경우 :
params.require(:measurement).permit!
모든 것이 예상대로 저장되지만 당연히 강력한 매개 변수가 제공하는 보안이 중단됩니다.
배열을 허용하는 방법을 찾았지만 중첩 된 객체를 사용하는 단일 예제는 없습니다. 꽤 일반적인 사용 사례이기 때문에 어쨌든 가능해야합니다. 어떻게 작동합니까?
중첩 속성을 허용 할 때 들리는 것처럼 이상하게도 배열 내에서 중첩 객체의 속성을 지정합니다. 귀하의 경우에는
@RafaelOliveira가 제안한대로 업데이트
params.require(:measurement)
.permit(:name, :groundtruth => [:type, :coordinates => []])
반면에 여러 객체를 중첩하려면 해시 안에 래핑합니다.
params.require(:foo).permit(:bar, {:baz => [:x, :y]})
레일즈는 실제로 이것에 대해 꽤 좋은 문서를 가지고 있습니다 : http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit
자세한 설명을 위해 https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/strong_parameters.rb#L246-L247 의 구현 permit
및 strong_parameters
자체를 살펴볼 수 있습니다.
이 제안이 내 경우에 유용하다는 것을 알았습니다.
def product_params
params.require(:product).permit(:name).tap do |whitelisted|
whitelisted[:data] = params[:product][:data]
end
end
github에 대한 Xavier의 의견 링크 를 확인하십시오 .
이 방법은 전체 params [: measurement] [: groundtruth] 객체를 허용합니다.
원래 질문 속성 사용 :
def product_params
params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
whitelisted[:groundtruth] = params[:measurement][:groundtruth]
end
end
중첩 된 객체 허용 :
params.permit( {:school => [:id , :name]},
{:student => [:id,
:name,
:address,
:city]},
{:records => [:marks, :subject]})
Rails 5 인 경우 새로운 해시 표기법으로 인해 params.permit(:name, groundtruth: [:type, coordinates:[]])
제대로 작동합니다.
참고 URL : https://stackoverflow.com/questions/18436741/rails-4-strong-parameters-nested-objects
'IT' 카테고리의 다른 글
Java 8-Optional.flatmap과 Optional.map의 차이점 (0) | 2020.06.28 |
---|---|
wget을 사용하여 전체 디렉토리와 하위 디렉토리를 다운로드하는 방법은 무엇입니까? (0) | 2020.06.28 |
코드로 조각 태그를 설정하는 방법은 무엇입니까? (0) | 2020.06.28 |
Java에서 String 클래스가 final로 선언 된 이유는 무엇입니까? (0) | 2020.06.28 |
PHP에서 두 문자열의 차이점을 강조 (0) | 2020.06.28 |