belongs_to vs HasMany

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值