2011-10-12 82 views
1

我将如何去获得与ActiveRecord的查询,连接(Rails的3.1)

[ 
    { 
    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 
    } 
] 

JSON对象通过一些关键的排序为给定user_entity对象(可以在任一属性或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

也许我错过了一些东西。你的财产为什么不也参考消费者?你有很多,你只是没有完成它。只需添加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