[英]Rails way to query on many-to-many privileges
我有一个用户和商店的应用程序,以及通过users_stores表的多对多关联。 其中一个商店的经理已登录,我需要向他们展示来自商店的用户的用户列表。
我想知道在Active Record中是否有Rails方法可以做到这一点?
使用连接查询相对容易
SELECT * FROM users, users_stores
INNER JOIN ON users.id = user_stores.user_id
WHERE store_id IN [1,2]
我想我知道如何使用活动记录来编写它,但如果管理员和用户都与相同的两个商店相关联,则会有重复的用户。 我也可以用子查询来编写它:
SELECT * FROM users
WHERE ( SELECT COUNT(*) FROM users_stores
WHERE user.id = users_stores.user_id
AND store_id IN [1,2] ) > 0
但是我不知道如何在活动记录中写出那个。
有没有办法用活动记录进行第二次查询,或者我应该只运行第一个查询,然后在本地处理结果以删除重复项?
简短的回答:我会在当地做。
class User < ActiveRecord::Base
has_many :stores do
# eager load appropriately or kill your db
def users
@users ||= inject([]){|users, store| users.concat store.users}.uniq
end
end
end
使用这样:
@user.stores.users
编辑 :使用ActiveRelation
,再一次db命中。 用法相同,但允许你做@user.stores.users.where(:pants => 'fancy')
类的ActiveRelation
。
class Store < ActiveRecord::Base
class << self
def users
User.where(:id => includes(:users).map{|store| store.users.map(&:id)})
end
end
end
Active Record提供多对多的关系:
用户模型
has_many :user_stores
has_many :stores :through => user_stores
商店模型
has_many :user_stores
has_many :users :through => user_stores
然后你可以通过调用: @user.stores
或@store.users
来获取用户的所有商店
在rails中,您需要定义模型中表之间的关系。 您可以使用has_and_belongs_to_many
或has_many
与:through
选项定义n..n关系。
您可以在关联文档中阅读更多相关信息:
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
在你的情况下,它可能是这样的:
User
模型:
has_and_belongs_to_many :stores
Store
型号:
has_and_belongs_to_many :users
完成后,您只需find
一个对象并像这样调用关联:
@user=User.find(params[:id])
@user.stores # Will return the associated stores
或者反过来说:
@store=Store.find(params[:id)
@store.users # Will return the associated users
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.