如何使用
获取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
}
]
为给定的user_entity对象按某个键(可以是Property或PropAssignmConsumer中的字段)排序?即获取链接到给定consumer / user_entity的所有属性,从属性和prop_assignm_consumers中提取字段,按属性或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
但这似乎效率不高......
任何帮助都将不胜感激。
答案 0 :(得分:0)
也许我错过了什么。为什么您的财产也没有引用消费者?你有很多很多,你只是没有完成它。只需添加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
REF http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html