The following are the models and association.
class Vendor < ActiveRecord::Base
attr_accessible :name, :address_attributes
has_many :campaigns
has_many :clients, :through => :campaigns
end
class Client < ActiveRecord::Base
attr_accessible :name
has_many :campaigns
has_many :vendors, :through => :campaigns
end
class Campaign < ActiveRecord::Base
attr_accessible :name, :vendor_id, :client_id, :start_date, :end_date
belongs_to :client
belongs_to :vendor
end
And this is the new campaign create form - form_for @campaign do |f| = f.error_messages %p = f.label :name %br = f.text_field :name %p = f.label :client_id, "Client" %br = f.collection_select(:client_id, Client.all, :id, :name, {:prompt => "Please select the client"}, {:class => "client_list"})
Now, the association method @vendor.clients
will just list the clients through the campaign
join model.
If the campaign table is blank, there ain't any clients
I can get with @vendor.clients
But as you see in the collection_select
in the new campaign form, I have to be able to choose the clients that belong to the vendor. So, I had to put the Client.all
call.
Though it renders the collection select, all those clients will be listed though they don't belong to that vendor.
So, to get/create/associate the clients and vendors with each other and to get @vendor.clients
though the campaign
is not created, I had to add another many to many association between vendors and clients, right?
If I do create the habtm association, it will conflict with each other, right?
class Vendor < ActiveRecord::Base
attr_accessible :name, :address_attributes
has_many :campaigns
has_many :clients, :through => :campaigns
has_and_belongs_to_many :clients
end
class Client < ActiveRecord::Base
attr_accessible :name
has_many :campaigns
has_many :vendors, :through => :campaigns
has_and_belongs_to_many :vendors
end
How am I gonna solve this? coz now, if I do, @vendor.clients
or @client.vendors
, which association gets called?
The one with has_and_belongs_to_many
or has_many: .., :through => ..