ITeye博客

belongs_to vs HasMany

sp42 · 2007-10-24 22:33 · Markdown

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

Updated on September 24, 2007 10:29 by Anonymous Coward (131.246.195.18)

Ruby on Rails has_many

The has_many association provides a way to access a one way relation between two tables.

Examples of this:

  • Companies database, where a company may have many accounts.
  • Forum System, where a category has many forums, which has many topics.

Example Forum

See ForumExample.

See Also

Notes

The finder_sql option in has_many should be in single quotes if you want inline variables (e.g. ‘SELECT * FROM something WHERE user_id = #{id}’) to be evaluated properly!

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。