开发者

1 has_many:.., :through and 1 has_and_belongs_to_many: .. problem?

开发者 https://www.devze.com 2022-12-28 02:21 出处:网络
The following are the models and association. class Vendor < ActiveRecord::Base attr_accessible :name, :address_attributes

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 => ..


You can rename your associations. In Vendor model:

has_many :campaign_clients, :through => :campaigns, :class_name => 'Client', :source => :client

and in Client model:

has_many :campaign_vendors, :through => :campaigns, :class_name => 'Vendor', :source => :vendor

Then, for example, vendor.clients will trigger the habtm association, and vendor.campaign_clients will trigger the :through association.

0

精彩评论

暂无评论...
验证码 换一张
取 消