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?