반응형
Ruby on Rails-여러 모델에 대한 JSON 렌더링
JSON에서 둘 이상의 모델의 결과를 렌더링하려고합니다. 내 컨트롤러의 다음 코드는 첫 번째 결과 집합 만 렌더링합니다.
def calculate_quote
@moulding = Moulding.find(params[:id])
@material_costs = MaterialCost.all
respond_to do |format|
format.json { render :json => @moulding }
format.json { render :json => @material_costs }
end
end
어떤 도움이라도 대단히 감사하겠습니다.
이를 수행 할 수있는 한 가지 방법은 렌더링하려는 개체로 해시를 만든 다음이를 render 메서드에 전달하는 것입니다. 이렇게 :
respond_to do |format|
format.json { render :json => {:moulding => @moulding,
:material_costs => @material_costs }}
end
모델이 활성 레코드를 통해 연결되지 않은 경우 이것이 아마도 최상의 솔루션 일 것입니다.
연관이있는 경우 다음과 :include
같이 렌더링 호출에 인수를 전달할 수 있습니다 .
respond_to do |format|
format.json { render :json => @moulding.to_json(:include => [:material_costs])}
end
@material_costs
이 방법을 사용하면 위 섹션 에서 변수 를 검색 할 필요가 없습니다 . Rails는 @moulding
변수 에서 자동으로로드합니다 .
컨트롤러는 하나의 응답 만 반환 할 수 있습니다. 이러한 모든 객체를 다시 보내려면 하나의 JSON 객체에 넣어야합니다.
어때 :
def calculate_quote
@moulding = Moulding.find(params[:id])
@material_costs = MaterialCost.all
response = { :moulding => @moulding, :material_costs => @material_costs }
respond_to do |format|
format.json { render :json => response }
end
end
나는 뭔가를했다
respond_to do |format|
format.html # show.html.erb
format.json { render :json => {:cancer_type => @cancer_type, :cancer_symptoms => @cancer_symptoms }}
결과는 다음과 같습니다.
{"cancer_type":{"created_at":"2011-12-31T06:06:30Z","desc":"dfgeg","id":2,"location":"ddd","name":"edddd","sex":"ddd","updated_at":"2011-12-31T06:06:30Z"},"cancer_symptoms":[]}
그래서 작동합니다
감사합니다
참고 URL : https://stackoverflow.com/questions/4318962/ruby-on-rails-render-json-for-multiple-models
반응형
'developer tip' 카테고리의 다른 글
Python 'for'루프를위한 더 나은 방법 (0) | 2020.11.18 |
---|---|
std :: queue 반복 (0) | 2020.11.18 |
registerServiceWorker는 React JS에서 무엇을합니까? (0) | 2020.11.18 |
Hibernate Criteria API에서 SQL을 얻는 방법 (로깅을위한 * 아님 *) (0) | 2020.11.18 |
ContextMenu의 MenuItem에서 ElementName 바인딩 (0) | 2020.11.18 |