2014-07-09 4 views
0

두 개체, AB이 있습니다. 각각에는 relationshipA을 사용하여 다른 여러 가지가 있습니다. relationshipA은 속성이 propertyA입니다. 가져 오기를 수행 할 때 relationshipAA 또는 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, prop2prop3RelationshipA있다

다음은 콘솔 예입니다.

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'>]> 
+0

나는 당신이'id'에 따라'A'를 조회하지만 추가 할 필요가 있다고 생각'포함 (: B)'호출에'B's 모두가되도록 포함. 그래서 A.includes (: b) .find (params [: id])' – CWitty

+0

@CWitty id에 기반하여 'A'를 찾을 수 있어야합니다. 그러면'A '와 관련된'B'를'RelationshipA '를 사용하여 모두 가져와야합니다. 그러나, 그것은 단지'B'의 배열을 리턴 할 것이지만,'B'와'RelationshipA's 값을 가진 해시 배열이 필요합니다. – RileyE

+0

Checkout http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations 도움이 될 수 있습니다. 내가 추천 한 제안은 A 객체와 B 객체 모두를 포함해야합니다. – CWitty

답변

1

나는이 개 질문을 참조하십시오

  1. 어떻게
  2. 가 어떻게 사용자 정의 JSON을 생성하는 객체를 돌려 보내야 할 사용자 정의 JSON을 생성합니까?

    class A < ActiveRecord::Base 
        has_many :relationships, :inverse_of :a 
        has_many :bs, :through => :relationships 
    end 
    
    class B < ActiveRecord::Base 
        # prop1 
        has_many :relationships, :inverse_of :b 
        has_many :as, :through => :relationships 
    end 
    
    class Relationship < ActiveRecord::Base 
        # prop4 
        belongs_to :a, inverse_of: :relationships 
        belongs_to :b, inverse_of: :relationships 
        def as_json(options: {}) 
        { 
         prop1: b.prop1, 
         prop4: prop4 
        } 
        end 
    end 
    
    relationships = A.includes(relationships: :b).find(params[:id]).relationships 
    puts relationships.to_json 
    

    문제는 매우 추상적입니다 :

사용자 정의 JSON 방법을 정의. Relationship 개체를 사용할 수 있다면 가장 좋은 방법 일 것입니다. includes을 사용하면 하나 또는 두 개의 검색어가 제공됩니다.

당신이 다시 B 가져 방법의 지식을 가진 B을해야하는 경우

는, 그때는 아마 Battr_accessor :prop4을 추가 할 및 Relationshiphas_many 절에 "확장"블록 B의 :prop4을 설정할 수 있습니다.

+0

내 질문을 콘솔 예제로 업데이트했습니다. 바라건대 그것은 명확히하는 데 도움이 될 수 있습니다. 나는 두 가지 예를 모두 시도했지만 도움을받지 못했습니다. – RileyE

0

내가 할 수있는 최선의 방법은 값의 해시이지만 초기 쿼리 또는 내장 함수를 사용하는 것이 아닙니다. @kbrock는 확실한 답변을 가지고 있지만, 나는 attributes 접근 방식을 선호합니다. 내가 제대로 이해하고있는 경우

class A < ActiveRecord::Base 
    has_many :relationships, :inverse_of :a 
    has_many :bs, :through => :relationships 

    # returns array of hashes, not json string, of all Relationship's and B's attributes 
    def relationshipValues 
    # get all of a's relationships, including `b`s with only 2 queries 
    relationships = Relationship.includes(:b).where(a_id: :id).all 
    relationshipValues = [] 
    # I'm not sure if this is optimal, so please offer some advice 
    @relationships.each do |relationship| 
     relationshipValues << relationship.attributes.merge(relationship.b.attributes) 
    end 
    # simple return - is there better way? 
    relationshipValues 
    #just for spacing :) 
    end 

end 

class B < ActiveRecord::Base 
    has_many :relationships, :inverse_of :b 
    has_many :as, :through => :relationships 
end 

class Relationship < ActiveRecord::Base 
    belongs_to :a, inverse_of: :relationships 
    belongs_to :b, inverse_of: :relationships 

    def to_json 
    attributes.merge(b.attributes) 
    end 
end