【发布时间】:2014-07-09 18:47:56
【问题描述】:
我有两个对象,A 和 B。每个都有很多其他的,使用relationshipA。 relationshipA 有一个属性 propertyA。我可以在执行提取时合并relationshipA 和A 或B 的属性吗?
例如
A.find(params[:id]).relationshipAs
我希望它返回Bs,但也将relationshipA 中的属性附加到它们中,至少在呈现 json 时是这样。
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 具有属性 prop1、prop2 和 prop3 和 RelationshipA 具有 prop4,我想从以下位置获得 json 响应:
render json: A.find(params[:id]).bs
我希望:
[{
'prop1' : 'value',
'prop2' : 'value',
'prop3' : 'value',
'prop4' : 'value'
}, ...]
这是一个控制台示例:
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,然后将includes(:b)添加到调用中,以便包含所有Bs。所以A.includes(:b).find(params[:id]) -
@CWitty 我需要能够根据 id 找到
A。然后我需要使用RelationshipA获取与A关联的所有Bs。但是,这只会返回一个Bs 数组,但我需要一个包含B和RelationshipAs 值的哈希数组。 -
结帐guides.rubyonrails.org/… 可能会有所帮助。我推荐的建议应该包括A的A对象和B对象。
-
在您的控制台示例中,我认为您仍然需要在 a1.bs = [b1, b2] 之后调用 a1.save
标签: ruby-on-rails json ruby-on-rails-4 associations