【问题标题】:How can I use eager loading in this case?在这种情况下如何使用急切加载?
【发布时间】:2013-08-29 09:30:34
【问题描述】:

假设我有这 6 个模型,例如

  • 用户
  • 简介
  • 性别
  • 国家
  • 县
  • 汽车

User 有一个Profile。
那么每个Profile有gender_id、country_id和prefecture_id的那些。
User也有很多Cars

我是这样声明关联的。

models/user.rb

has_one :profile
has_many :cars

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

models/profile.rb

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

models/gender.rb

has_many :user_profile

models/country.rb

has_many :user_profile

models/prefecture.rb

has_many :user_profile

models/car.rb

belongs_to :user

这是我的问题!
如何在控制器中修复我的代码并查看?

这是我当前的代码。

控制器

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

查看

<% @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 或1 存储在您的gender 列中并创建一个GENDERS 常量来将您的整数映射到性别。 GENDERS = { 0 =&gt; 'male', 1 =&gt; 'female' } 为永不改变的数据创建数据库表是没有意义的。这样做也会使您的查询更轻松、更快捷。
  • 这是有道理的。谢谢

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

更新

我想,你应该试试这个方法:

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

有效吗?

【讨论】:

  • 能否请您在控制器中自定义我的原始代码?我不知道如何将您的代码添加到我原来的代码中
  • @users = User.includes(:cars, profile: [:gender, :country, :prefecture]).page(params[:page]).order('profiles.total_point DESC')有用吗?
  • 更多细节在这里:guides.rubyonrails.org/…
  • 非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-30
  • 2021-09-15
  • 1970-01-01
  • 2022-01-23
  • 2015-11-30
  • 2017-05-16
相关资源
最近更新 更多