2013-08-29 56 views
0

假設我有這6款車型,如如何在這種情況下使用急切加載?

  • 用戶
  • 簡介
  • 性別
  • 國家

User有一個Profile
然後,每個Profile都有gender_id,country_idprefecture_id
User也有很多Cars

我說的就是這樣的asssociation。

型號/ user.rb

has_one :profile 
has_many :cars 

scope :confirmed, where("sign_in_count != ?",0) 
paginates_per 10 

型號/ profile.rb

belongs_to :user 
belongs_to :gender 
belongs_to :country 
belongs_to :prefecture 

型號/ gender.rb

has_many :user_profile 

型號/ country.rb

has_many :user_profile 

型號/ prefecture.rb

has_many :user_profile 

型號/ car.rb

belongs_to :user 

這是我的問題!
我該如何解決我的代碼在控制器中,並查看?

這是我目前的代碼。

控制器

@users = User.confirmed.joins(:profile).page(params[:page]).order('profiles.total_point DESC') 

VIEW

<% @users.each do |user| %> 
    <tr> 
     Username: <%= user.username %> <br /> 
     Total Point: <%= user.profile.total_point %> <br /> 
     Gender: <%= user.profile.gender.data %> <br /> 
     Country: <%= user.profile.country.data %> <br /> 
     Prefecture: <%= user.profile.prefecture.data %> <br /> 
     The number of the cars that the user owns: <%= user.cars.count %> <br /> 
    </tr>   
<% end %> 
+0

爲什麼性別是一個單獨的模型?明天不會有任何新的性別。在我看來,它應該只是用戶的一個屬性。 – Mischa

+0

,因爲我希望將它作爲總結性能目標的數字(整數) – HUSTEN

+1

因此,只需在'gender'列中存儲'0'或'1'並創建一個'GENDERS'常量來將您的整數映射到性別。 'GENDERS = {0 =>'male',1 =>'female'}'爲永不改變的數據創建數據庫表是沒有意義的。這樣做也會使您的查詢變得更加簡單快捷。 – Mischa

回答

1

更新

我想,你應該試試這種方法:

@users = User.includes(:cars, profile: [:gender, :country, :prefecture]).confirmed.page(params[:page]).order('profiles.total_point DESC') 

它工作嗎?

+0

可以請你在控制器中定製我的原始代碼?我無法弄清楚如何將你的代碼添加到我的原始代碼 – HUSTEN

+0

那麼'car'模型呢?你不能將它添加到代碼? – HUSTEN

+1

@users = User.includes(:cars,profile:[:gender,:country,:prefecture])。page(params [:page])。order('profiles.total_point DESC') 它工作嗎? – hedgesky