在 Rails 3 中重构 activerecord 方法
这个事件方法可以重构和简化吗?
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
我希望我可以在我当前拥有的 Manager 实例之上构建查询,但似乎无法做到这一点。我尝试了以下操作,但出现错误
def events
customers.joins(:events).select("DISTINCT(events.id), events.description, events.created_at")
end
,
current_user.events
但这会导致 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
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. 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:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据MySQL手册,DISTINCT关键字必须出现在select_expr:
会给你这个错误。
会起作用的。试试这个:
但是,如果您想做的只是获取每个用户的唯一事件(我认为这就是 DISTINCT 的用途),您可以使用
According to the MySQL manual, the DISTINCT keyword must come before the select_expr:
will give you that error.
will work. Try this:
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