Pattern for unidirectional has_many join?
Posted
by Kris
on Stack Overflow
See other posts from Stack Overflow
or by Kris
Published on 2009-06-02T16:04:59Z
Indexed on
2010/04/05
22:03 UTC
Read the original article
Hit count: 172
It occurred to me that if I have a has_many join, where the foreign model does not have a belongs_to, and so the join is one way, then I don't actually need a foreign key.
We could have a column, category_ids, which stores a marshaled Array of IDs which we can pass to find
.
So here is an untested example:
class page < AR
def categories
Category.find(self.category_ids)
end
def categories<<(category)
# get id and append to category_ids
save!
end
def category_ids
@cat_ids ||= Marshal.load(read_attribute(:category_ids)) rescue []
end
def category_ids=(ids)
@cat_ids = ids
write_attribute(:category_ids, ids)
end
end
page.category_ids => [1,4,12,3] page.categories => Array of Category
Is there accepted pattern for this already? Is it common or just not worth the effort?
© Stack Overflow or respective owner