Reputation: 2974
Alright, a Rails Noob here, :D
It looks like has__many :through is the latest greatest way to handle many to many relationships, but I am trying to keep this simple. Hopefully one of you guru's out there have handled this situation before:
Here is the basic model setup I have now:
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
Essentially, I have users in the system, that will have access (through association) to many different products that are being created, those products have many clients, but the clients can also be a part of many products, and the Products accessed by many users.
All of the associations are working well, but now I want users to be able to add clients to their products, but only see clients that are associated with products they have access too.
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
My noobish experience with rails fails to give me the experience on how to best build the array that will hold his client list.
The way I am thinking be to use @bob.products to get the products Bob has access to then to .each those and find the clients associated with each product and then join them into a single array. But is this the BEST way?
Thanks!
Upvotes: 1
Views: 242
Reputation:
Not sure if this is what you're looking for, but if you want to remove all non-authorized clients for a particular user:
user = current_user
@clients_access = Array.new
user.products.each { |p| @clients_access.push(p.clients).uniq! }
@clients_access.flatten!
Upvotes: 1
Reputation: 2974
Alright so I achieved the functionality I wanted by the following:
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
Basically, finding all the the clients, then iterating through the linked authorized products and removing them from the list, basically creating a list of non-authorized clients.. then doing the search again and clearing out the non-authorized clients and the clients already assigned in the group.. But, I have ran out of duct-tape.. any better solutions?
Upvotes: 0