Please explain rails has_many through association -
i'm trying understand rails associations
i've following tables , i've define relations, can 1 please me understand. tables products, productdistributors, , distributors. every product has distributor, distributor carries multiple products
i defined these
class product < activerecord::base has_one :product_distributor has_one :distributor, through: :product_distributor end class productdistributor < activerecord::base belongs_to :products belongs_to :distributors end class distributor < activerecord::base has_many :product_distributors has_many :products, through: :product_distributors end
is correct? if not, how can correct it?
i feel problem lies in distributors
class name because it's plural. when has_many :distributors
, rails default link distributor
class, in case class name distributors
.
adding class_name
option relationship declarations should work:
class product < activerecord::base has_one :product_distributor has_one :distributor, through: :product_distributor, class_name: 'distributors' end class productdistributor < activerecord::base belongs_to :product belongs_to :distributor, class_name: 'distributors' end class distributors < activerecord::base has_many :product_distributors has_many :products, through: :product_distributors end
also note belongs_to
should singular not plural. please go through association guide details: http://guides.rubyonrails.org/association_basics.html.
Comments
Post a Comment