【问题标题】:Rewrite rails model method to ActiveRecord request将 Rails 模型方法重写为 ActiveRecord 请求
【发布时间】:2013-09-26 10:36:32
【问题描述】:

User has_many micropostsMicropost belongs to users

获取微博数超过 10 条的用户

控制器:

def active_users
  @users  = User.active_users
end

型号

def self.active_users
  self.select { |u| u.microposts.size > 10}
end

如何将方法 active_users 重写为 ActiveRecord 请求(可能使用 :count :group 方法)

                             **UPDATE**

the solution

self.joins(:microposts).group("users.id").having("count(*) > 10").all

【问题讨论】:

  • 是的答案在**UPDATE**下方

标签: ruby-on-rails-3 activerecord


【解决方案1】:

Counter_Cache 是您的答案。

也许可以这样做: http://railscasts.com/episodes/23-counter-cache-column http://guides.rubyonrails.org/association_basics.html#counter-cache

User has_many microposts

Micropost 
  belongs to users
  counter_cache: true

然后进行迁移:

class AddMicropostCountToUsers < ActiveRecord::Migration
  def change
    add_column :users, :microposts_count, :integer
  end
end

然后你就可以去做类似的事情了。

@users  = User.where('microposts_count > ?', 10)

如需进一步定制,请查看链接。

【讨论】:

  • 在更新消息下查看我的任务,我将使用 AR 解决我的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-14
  • 1970-01-01
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 2010-10-31
  • 1970-01-01
相关资源
最近更新 更多