두 개체, A
및 B
이 있습니다. 각각에는 relationshipA
을 사용하여 다른 여러 가지가 있습니다. relationshipA
은 속성이 propertyA
입니다. 가져 오기를 수행 할 때 relationshipA
및 A
또는 B
의 속성을 병합 할 수 있습니까? 예를관계/연관 모델 값을 기본 모델에 추가
A.find(params[:id]).relationshipAs
를 들어
나는 JSON 렌더링 적어도 때 즉, 그들로 relationshipA
에서 속성을 나에게 Bs
를 반환 할뿐만 아니라 추가하고 싶습니다. 내가 기대하고 싶습니다
render json: A.find(params[:id]).bs
:
[{
'prop1' : 'value',
'prop2' : 'value',
'prop3' : 'value',
'prop4' : 'value'
}, ...]
class A < ActiveRecord::Base
has_many :relationship_a
has_many :b, through: :relationship_a
end
class B < ActiveRecord::Base
has_many :relationship_a
has_many :a, through: :relationship_a
end
class RelationshipA < ActiveRecord::Base
belongs_to :A
belongs_to :B
end
가정하면 B는 prop4
, 나는에서 JSON 응답을 좀하고 싶습니다했다 속성 prop1
, prop2
및 prop3
및 RelationshipA
있다
다음은 콘솔 예입니다.
a1 = A.create
b1 = B.create
b2 = B.create
a1.bs = [b1, b2]
RelationshipA.where(a_id: a1.id).first.prop4 = 'Hello'
RelationshipA.where(a_id: a1.id).last.prop4 = 'There'
*now output all of a1's bs including the relationships' prop4 value*
#<ActiveRecord::Associations::CollectionProxy [#<B id: 1, prop1: nil, prop2: nil, prop3: nil, created_at: "2014-07-09 20:37:12", updated_at: "2014-07-09 20:37:12", prop4: 'Hello'>, #<B id: 2, prop1: nil, prop2: nil, prop3: nil, created_at: "2014-07-09 20:37:12", updated_at: "2014-07-09 20:37:12", prop4: 'There'>]>
나는 당신이'id'에 따라'A'를 조회하지만 추가 할 필요가 있다고 생각'포함 (: B)'호출에'B's 모두가되도록 포함. 그래서 A.includes (: b) .find (params [: id])' – CWitty
@CWitty id에 기반하여 'A'를 찾을 수 있어야합니다. 그러면'A '와 관련된'B'를'RelationshipA '를 사용하여 모두 가져와야합니다. 그러나, 그것은 단지'B'의 배열을 리턴 할 것이지만,'B'와'RelationshipA's 값을 가진 해시 배열이 필요합니다. – RileyE
Checkout http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations 도움이 될 수 있습니다. 내가 추천 한 제안은 A 객체와 B 객체 모두를 포함해야합니다. – CWitty