好的,这里是Rails Noob,:D
看起来has__many :through是处理多对多关系的最新最好的方法,但我正在努力保持这一点。希望你们中的某位大师以前处理过这种情况:
这是我现在拥有的基本模型设置:
class User < ActiveRecord::Base
has_and_belongs_to_many :products
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :users
has_and_belongs_to_many :clients
end
class Client < ActiveRecord::Base
has_and_belongs_to_many :products
end本质上,我在系统中有用户,他们可以访问(通过关联)正在创建的许多不同的产品,这些产品有许多客户端,但这些客户端也可以是许多产品的一部分,许多用户可以访问这些产品。
所有的关联都工作得很好,但现在我希望用户能够将客户端添加到他们的产品中,但只能看到与他们有权访问的产品相关联的客户端。
Scenario:
Given Bob has access to product A and B
And does NOT have access to product C
And and has clients on product B
And wants to add them to product A.
When in product A Bob should see clients from product B in his add list,
And Bob should not see clients from product C我在rails方面的经验并不丰富,无法让我知道如何最好地构建包含他的客户列表的数组。
我的想法是使用@bob.products获取Bob有权访问的产品,然后对这些产品执行.each操作,找到与每个产品相关联的客户端,然后将它们加入到单个数组中。但这是最好的方法吗?
谢谢!
发布于 2009-09-18 16:06:04
不确定这是否是您要查找的内容,但如果您想要删除特定用户的所有未授权客户端:
用户= current_user
@clients_access = Array.new
user.products.each { |p| @clients_access.push(p.clients).uniq!}
@clients_access.flatten!
发布于 2009-09-17 22:47:56
好的,我通过下面的代码实现了我想要的功能:
user = current_user
@clients_no_access = Client.find(:all, :order => :business_name)
user.products.each do |product|
@clients_no_access -= product.clients
end
@all_clients = Client.find(:all,
:order => :business_name) - @clients_no_access - @product.clients基本上,找到所有客户端,然后迭代链接的授权产品并将其从列表中删除,基本上创建了一个非授权客户端的列表。然后再次进行搜索,并清除未授权的客户端和已分配到组中的客户端。但是,我的胶带用完了..有更好的解决方案吗?
https://stackoverflow.com/questions/1441303
复制相似问题