1

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?

4

2 回答 2

1

当您编组/解组时,性能不会在这里受到影响吗?

我个人认为这不值得付出努力,而且您要尝试做的事情似乎还不清楚。

实际上,这看起来像一个多对多映射而不是多对一,因为没有代码可以阻止一个类别属于多个页面,当然你想要这样的东西:

create table categories_pages (
  category_id integer not null references categories(id),
  page_id integer not null references pages(id),
  primary_key(category_id, page_id)
);

两边都有一个 has 和属于 many 或 has_many :through 在两边(取决于你是否想存储更多的东西)。

于 2009-06-02T20:10:11.500 回答
1

我同意奥马尔的观点,这似乎不值得付出努力。

您的数据库不再反映您的数据模型,并且不会为加强这种关系提供任何帮助。此外,如果您想限制与 has_many 的关系,您现在必须使编组后的 id 数组与 Category 表同步,并在 Pages 之间强制执行唯一性。

但我想最重要的是,这种方法有什么好处?这将增加复杂性并增加您必须编写的代码量。

于 2009-11-24T21:13:28.327 回答