假設我有這6款車型,如如何在這種情況下使用急切加載?
- 用戶
- 簡介
- 性別
- 國家
- 縣
- 車
User
有一個Profile
。
然後,每個Profile
都有gender_id
,country_id
和prefecture_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 %>
爲什麼性別是一個單獨的模型?明天不會有任何新的性別。在我看來,它應該只是用戶的一個屬性。 – Mischa
,因爲我希望將它作爲總結性能目標的數字(整數) – HUSTEN
因此,只需在'gender'列中存儲'0'或'1'並創建一個'GENDERS'常量來將您的整數映射到性別。 'GENDERS = {0 =>'male',1 =>'female'}'爲永不改變的數據創建數據庫表是沒有意義的。這樣做也會使您的查詢變得更加簡單快捷。 – Mischa