2007-10-24

belongs_to vs HasMany

关键字: ActiveRecord

Ruby on Rails belongs_to

belongs_to complements a has_many or has_one association.

In general, the Foo model belongs_to :bar if the foo table has a bar_id foreign key column.

Examples of this:

  • Companies database, where an account belongs to a company.
  • Forum system, where a topic belongs to a forum, which belongs to a category.
  • a gallery system where a thumbnail belongs to a picture.

Example Forum

See ForumExample.

Notes

When using :counter_cache => true, be sure the default value on your model_count column defaults to something that can be incremented. NULL + 1, for instance, equals NULL so the counter SQL won’t work.

You’d think this feature would make parent.child.count or parent.child.length use this cache, instead of issuing a new COUNT query. You’d be wrong.

See the API for more information about :counter_cache

Another way to think of this is to say “the foreign key in table abc belongs_to table def”.

Gotchas

Watch your plural versus singular! If you’re going between has_many and belongs_to, it’s easy to get mixed up with plurals and singulars. belongs_to definitely uses singular parameters, and will not print very convenient errors if not put correctly.

If you are using belongs_to across namespaces, you will definitely need to use the :class_name and :foreign_key modifiers to belongs_to.

Say you are saying your Model belongs_to MySpace::OtherModel


class Model
belongs_to :other_model # will NOT work
# The following WILL work
belongs_to :other_model,
:class_name => "MySpace::OtherModel",
:foreign_key => "other_model_id"
end

评论
发表评论

您还没有登录,请登录后发表评论

sp42
搜索本博客
博客分类
存档
最新评论