简体   繁体   English

在 Rails 3 中重构 activerecord 方法

[英]Refactoring an activerecord method in Rails 3

Can this events method be re-factored and simplified?这种事件方法可以重构和简化吗?

class Manager < User
  has_and_belongs_to_many :customers

  def events
    Event.joins(:customers => :managers).where(:users => { :id => self }).select("DISTINCT(events.id), events.description, events.created_at")
  end

end

I was hoping I could build the query on top of the Manager instance I currently have, but seem unable to do this.我希望我可以在我目前拥有的 Manager 实例之上构建查询,但似乎无法做到这一点。 I tried the following, but got an error我尝试了以下方法,但出现错误

def events
  customers.joins(:events).select("DISTINCT(events.id), events.description, events.created_at")
end

and

current_user.events

But this results in MySQL error:但这会导致 MySQL 错误:

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DISTINCT(events.id), events.description, events.created_at FROM `customers` INNER' at line 1: SELECT `customers`.*, DISTINCT(events.id), events.description, events.created_at FROM `customers` INNER JOIN `customers_events` ON `customers_events`.`customer_id` = `customers`.`id` INNER JOIN `events` ON `events`.`id` = `customers_events`.`event_id` INNER JOIN `customers_managers` ON `customers`.`id` = `customers_managers`.`customer_id` WHERE `customers_managers`.`manager_id` = 27 ORDER BY created_at DESC

According to the MySQL manual , the DISTINCT keyword must come before the select_expr:根据MySQL 手册,DISTINCT 关键字必须在 select_expr 之前:

SELECT foo.*, DISTINCT(foo.id) 

will give you that error.会给你那个错误。

SELECT distinct(foo.id), foo.*

will work.将工作。 Try this:尝试这个:

customers.select("DISTINCT(events.id), events.description, events.created_at").joins(:events)

However, if all you're trying to do is to get the unique events per user (I assume that's what the DISTINCT is for), you could just use但是,如果您要做的只是获取每个用户的唯一事件(我认为这就是 DISTINCT 的用途),您可以使用

current_user.events.group("events.id")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM