2011-10-12 104 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