has_many通过并选择顺序不起作用

时间:2013-12-11 22:09:41

标签: ruby-on-rails

我正在尝试列出用户并通过EventViews订购它们,但我一直收到错误:

Unknown column 'views_count' in 'order clause': SELECT `users`.`id` AS t0_r0, `users`.`email` AS t0_r1, `users`.`encrypted_password` AS t0_r2, `users`.`reset_password_token` AS t0_r3, `users`.`reset_password_sent_at` AS t0_r4, `users`.`remember_created_at` AS t0_r5, `users`.`sign_in_count` AS t0_r6, `users`.`current_sign_in_at` AS t0_r7, `users`.`last_sign_in_at` AS t0_r8, `users`.`current_sign_in_ip` AS t0_r9, `users`.`last_sign_in_ip` AS t0_r10, `users`.`created_at` AS t0_r11, `users`.`updated_at` AS t0_r12, `users`.`user_type` AS t0_r13, `event_views`.`id` AS t1_r0, `event_views`.`event_id` AS t1_r1, `event_views`.`ip` AS t1_r2, `event_views`.`created_at` AS t1_r3, `event_views`.`updated_at` AS t1_r4, `event_views`.`session_id` AS t1_r5, `event_views`.`is_unique` AS t1_r6, `event_views`.`user_agent` AS t1_r7, `event_views`.`promoter_id` AS t1_r8 FROM `users` LEFT OUTER JOIN `events` ON `events`.`user_id` = `users`.`id` LEFT OUTER JOIN `event_views` ON `event_views`.`event_id` = `events`.`id`  ORDER BY views_count desc

这是我的代码:

User.all.includes(:event_views).select('user.*, count(event_views.id) as "views_count"').order("views_count desc").each

#models

User
has_many :event_views, :through => :events

Events
has_many :event_views

EventView
#nothing relevant

它们都以正常方式相关(event_id,user_id等)

2 个答案:

答案 0 :(得分:0)

这里要记住几点:

  1. 您正在includes User.all上呼叫Array,这样会失败。
  2. 正如@peteralfvin已经指出的那样,你应该users.*而不是user.*。但这将是一个问题,因为您正在使用count聚合函数。这意味着您需要在users子句中的group by表中包含每一列。
  3. 在这种情况下,您不应该使用includes,因为includes将包含查询中所有包含的表中的所有列。这是因为您要从usersevent_views中选择列。如果您删除count(event_views.id) as "views_count",那么您将看到只会选择users表中指定的列。
  4. 话虽这么说,这个查询应该适合你:

    users = User.joins(:event_views).select('users.id, count(event_views.id) as views_count').order("views_count desc")
    # Then access your views_count for user with: 
    users.first.views_count
    

答案 1 :(得分:0)

如果你要获得所有记录,你真的不需要在SQL查询中这样做:

users = User.includes(:event_views).all
users.sort_by!{ |user| user.event_views.count }

如果您希望以另一种方式对它们进行排序,只需在最后一行的末尾添加.reverse!