has_xxx 和 belongs_to 的 :foreign_key 选项的默认值
1. has_one / has_many / has_and_belongs_to_many 的 :foreign_key 的默认值
has_one, has_many, has_and_belongs_to_many 的 :foreign_key 的默认值为以声明了此关联关系的模型类的类名的小写加
上 _id 。例如:一篇文章(model class: Article)有一个作者(model class: User)以及多个贡献者(model class: User),对
应的这个数据模型的migration 为:
1 | class CreateUsers < ActiveRecord::Migration |
1 | class CreateArticles < ActiveRecord::Migration |
1 | class CreateJoinTableArticlesContributors |
那么若要表示一个用户所主编的所有文章,需要在 User
模型类里添加以下的关联声明:
1 | class User < ActiveRecord::Base |
2. belongs_to 的 :foreign_key 的默认值
belongs_to 的默认值为关联关系的名称加上 _id 。例如,在上面的例子中,需要表示一篇文章有一个作者,那么需要在
Article 模型里添加以下的关联声明:
1 | class Article < ActiveRecord::Base |
因为 belongs_to 的 :foreign_key 选项的默认值为此关联关系的名称加上 _id ,即 author 加上 _id ,因此
article.rb中的 belongs_to :author, :class_name => :User, :foreign_key => :author_id 可以简化为 belongs_to :author,
:class_name => :User