如何使用
获取JSON对象?[
{
Property.field_1,
Property.field_n,
PropAssignmConsumer.field_1,
PropAssignmConsumer.field_n
},
{
Property.field_1,
Property.field_n,
PropAssignmConsumer.field_1,
PropAssignmConsumer.field_n
},
...,
{
Property.field_1,
Property.field_n,
PropAssignmConsumer.field_1,
PropAssignmConsumer.field_n
}
]
排序的一些关键(可以在属性或PropAssignmConsumer字段)为给定的user_entity对象?例如,获取链接到给定消费者/user_entity的所有属性,从properties和prop_assignm_consumers中提取字段,按properties或prop_assignm_consumer表中的字段排序。
这些是我的模型:
class Property < ActiveRecord::Base
has_many :prop_assignm_consumers, :dependent => :restrict
end
class PropAssignmConsumer < ActiveRecord::Base
belongs_to :consumer
belongs_to :property
end
class Consumer < UserEntity
has_many :prop_assignm_consumers, :dependent => :destroy
has_many :properties, :through => :prop_assignm_consumers
end
我正在做
properties = user_entity.properties.find(:all, :order => "#{sort_key} #{sort_ord}")
properties.each do |p|
a = p.prop_assignm_consumers.find_by_consumer_id(current_user.user_entity.id)
... do something with a and p....
end
但这似乎效率不高....
也许我错过了什么。为什么你的财产没有提到消费者?你有很多对很多,你只是没有完成它。只要加上has_many :consumers, :through => :prop_assignm_consumer
就可以做
properties = user_entity_properties.all(:include => :consumers)
properties.each do |p|
p.consumers.where(:id => current_user.user_entity.id)
end
虽然现在我们写了这个,并且考虑到你做的是find_by而不是find_all_by,很明显只有1。所以你可以走另一条路。
consumer = Consumer.where(:id => current_user.user_entity.id).includes(:properties).first
consumer.properties.each do |p|
... do something with p and consumer
end
裁判http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html