问题
Is there a way to produce an optional many to many relationship in rails?
I have a Client
model and a ClientManager
model - And I want a Client
to have 0, 1 or many client_managers
. But I'd also like a Clientmanger
to be able to have 0, 1 or more clients
. Is this possible? And how?
Using rails 5.
Updated for clarity/purpose: I want clientmanagers, to be able to manage multiple clients, or even none. And clients to be able to be managed by 0, 1 or multiple client-managers
回答1:
If it's an NxN relationship, you should create another model that belongs to both Client and ClientManager. Let's call it Management, for instance:
rails g model Management client:references client_manager:references
That would generate something like this:
class Management < ActiveRecord::Base
belongs_to :client
belongs_to :client_managers
end
and then, on your Client model:
has_many :managements
has_many :client_managers :through => :managements
and on your ClientManager:
has_many :managements
has_many :clients :through => :managements
Hope this helps you figure out. Good Luck!
回答2:
You can also use has_and_belongs_to_many association.
Your models would be
class Client < ActiveRecord::Base
has_and_belongs_to_many :managers
end
class Manager< ActiveRecord::Base
has_and_belongs_to_many :clients
end
回答3:
this is a straightforward many-to-many relationship with has_many through
relation between Client
and ClientManager
data models. For this, you need to setup 3 tables in your db clients
, client_managers
, projects
# models/client.rb
class Client < ApplicationRecord
has_many :projects
has_many :client_managers, through: :projects
end
# models/project.rb
# projects table schema should have- client_id:integer client_manager_id:integer
class Project < ApplicationRecord
belongs_to :client
belongs_to :client_manager
end
# models/client_manager.rb
class ClientManager < ApplicationRecord
has_many :projects
has_many :clients, through: :projects
end
Access
Client.last.client_managers
gives 0, 1 or many client_managers associated with Client.last
ClientManager.last.clients
gives 0, 1 or many clients associated with ClientManager.last
more info here
来源:https://stackoverflow.com/questions/40888515/optional-many-to-many-relationship-in-rails