随着Rails 3.1.3
on Ruby 1.9.2
,我有:
class User < ActiveRecord::Base
has_and_belongs_to_many :states
end
class State < ActiveRecord::Base
has_and_belongs_to_many :users
end
AUser
与 many State
s 相关联,aState
与 many User
s 相关联。给定 a User
,我想找到User
在她的任何一个州的所有其他 s。
我试过:
class User < ActiveRecord::Base
scope :in_state, lambda { |states| joins(:states).where(:states => states) }
end
User.in_state(current_user.states).all
出现此错误(为便于阅读而格式化):
Mysql2::Error: Not unique table/alias: 'states_users':
SELECT COUNT(*)
FROM `users`
INNER JOIN `states_users` ON `states_users`.`user_id` = `users`.`id`
INNER JOIN `states` ON `states`.`id` = `states_users`.`state_id`
LEFT OUTER JOIN states_users on users.id = states_users.user_id AND states_users.state_id IS NULL
WHERE `states`.`id` IN (8)
我意识到我需要一些方法来为其中一个states_users
引用设置别名,但我不知道如何使用scope
.
这是我要编写的 SQL:
SELECT u2.*
FROM users u
INNER JOIN states_users su ON su.user_id = u.id
INNER JOIN states s ON s.id = su.state_id
INNER JOIN states_users su2 ON s.id = su2.state_id
INNER JOIN users u2 ON u2.id = su2.user_id
WHERE u.id = 771
想法?
谢谢。
更新 12/14/2011 @ 10:48 AM:
这是有效的:
scope :in_states_of, lambda { |user|
joins('INNER JOIN states_users su ON su.user_id = users.id ' +
'INNER JOIN states s ON s.id = su.state_id ' +
'INNER JOIN states_users su2 ON s.id = su2.state_id ' +
'INNER JOIN users u ON u.id = su2.user_id').
where("u.id = ?", user.id) }
User.in_states_of(current_user)
它不是特别优雅,但它正在工作。您必须users
为“传入”的引用设置别名,User
以便可以将此范围与其他范围链接,例如:
scope :active, where(active => true)
User.in_states_of(current_user).active
任何改进建议都将受到欢迎。