ruby on rails - How can I setup a has_many associated to look in 2 columns in a db table (category_a_id and category_b_id) -
i need able link categories
each other.
i have category_links
table 2 columns category_a_id
, category_b_id
hold id
of 2 categories linked.
i want able call category.find(1).category_links
, grab records id 1 both category_a_id
, category_b_id
columns. if category destroyed delete associated records in category_link
db if associated in category_a_id
or category_b_id
column.
currently in category_links
model have
belongs_to :category_b, :class_name => :category belongs_to :category_a, :class_name => :category
and in category db
has_many(:category_links, :foreign_key => :category_a_id, :dependent => :destroy) has_many(:category_links, :foreign_key => :category_b_id, :dependent => :destroy)
but assosiates records category_b_id
column matching id not both. calling category.find(1).category_links
doesnt grab records matching both category_a_id
, category_b_id
. same goes destroying category.
how can work if destroy category looks both columns associated category , calling category.find(1).category_links
looks in both columns matching record?
there's no simple way achieve through has_many
, if don't have fancy create custom method on category
:
def category_links @category_links ||= categorylinks.where('category_a_id = ? or category_b_id = ?', id, id) end
Comments
Post a Comment