레일에서 JSON을 렌더링할 때 관련 모델 포함
지금 이 순간은 다음과 같습니다.
render json: @programs, :except => [:created_at, :updated_at]
단, 프로그램은 회사에 소속되어 있기 때문에 회사 ID가 아닌 회사명을 표시하고 싶습니다.
프로그램을 렌더링할 때 회사 이름을 포함하려면 어떻게 해야 합니까?
다음과 같은 것이 동작합니다.
render :json => @programs, :include => {:insurer => {:only => :name}}, :except => [:created_at, :updated_at]
컨트롤러 메서드에서 포함을 사용하여 json을 렌더링하는 동안 동일한 "심볼 파일을 복제할 수 없습니다" 오류가 발생했습니다.그렇게 피했다.
render :json => @list.to_json( :include => [:tasks] )
모델 수준에서도 이 작업을 수행할 수 있습니다.
프로그램.개요
def as_json(options={})
super(:except => [:created_at, :updated_at]
:include => {
:company => {:only => [:name]}
}
)
end
end
이제 컨트롤러:
render json: @programs
jbuilder를 사용하여 유지 보수 가능한 방식으로 중첩된 모형을 포함하십시오.
# /views/shops/index.json.jbuilder
json.shops @shops do |shop|
# shop attributes to json
json.id shop.id
json.address shop.address
# Nested products
json.products shop.products do |product|
json.name product.name
json.price product.price
end
end
이거 먹어봐.참조
#`includes` caches all the companies for each program (eager loading)
programs = Program.includes(:company)
#`.as_json` creates a hash containing all programs
#`include` adds a key `company` to each program
#and sets the value as an array of the program's companies
#Note: you can exclude certain fields with `only` or `except`
render json: programs.as_json(include: :company, only: [:name])
또, 할 필요가 없다.@programs
인스턴스 변수(instance variable)는 뷰에 전달하지 않는 것으로 가정합니다.
#includes is used to avoid n+1 query.
# http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
Here is an example for the above example.Lets say you have posts and each post has many comments to it.
@posts = Post.where('id IN [1,2,3,4]').includes(:comments)
respond_to do |format|
format.json {render json: @posts.to_json(:include => [:comments]) }
end
#output data
[
{id:1,name:"post1",comments:{user_id:1,message:"nice"}}
{id:2,name:"post2",comments:{user_id:2,message:"okok"}}
{id:3,name:"post1",comments:{user_id:12,message:"great"}}
{id:4,name:"post1",comments:{user_id:45,message:"good enough"}}
]
언급URL : https://stackoverflow.com/questions/17730121/include-associated-model-when-rendering-json-in-rails
'programing' 카테고리의 다른 글
슈퍼키, 후보키 및 프라이머리 키 (0) | 2023.02.23 |
---|---|
Postgre를 사용하여 데이터 소스를 생성할 때 예외 발생Spring Boot SQL 드라이버 (0) | 2023.02.23 |
Json을 반환하지만 원하지 않는 뒤로 슬래시 "\"를 포함합니다. (0) | 2023.02.23 |
WooCommerce - URL에서 제품 및 제품 카테고리를 삭제하는 방법 (0) | 2023.02.23 |
문자열 배열에서 Orderby 필터를 작동시키는 방법은 무엇입니까? (0) | 2023.02.23 |