Rails model one-to-many relationships

已销号 发布于 2015/05/18 12:56
阅读 156
收藏 3

Base on Rails 4.xxx

在表关联中,一对多关联的使用情景比较频繁;譬如一个用户拥有多篇博客文章,一篇文章只属于一位作者。那么在Rails中,我们该如何实现呢?

If you are using the Rails 4.x you can now generate migrations with references, like this:

rails generate migration AddUserRefToProducts user:references

rake db:migrate之后,这会在products表中生成user_id字段。

详细举个栗子:

rails g migration AddUserRefToPosts user:references

生成数据库迁移文件:

class AddUserRefToPosts < ActiveRecord::Migration
  def change
    add_reference :posts, :user, index: true
    add_foreign_key :posts, :users
  end
end
执行
rake db:migrate
huxi git:(master) ✗ rake db:migrate
== 20150518043748 AddUserRefToPosts: migrating ================================
-- add_reference(:posts, :user, {:index=>true})
   -> 1.6237s
-- add_foreign_key(:posts, :users)
   -> 0.5118s
== 20150518043748 AddUserRefToPosts: migrated (2.1358s) =======================
最后在model中编写user和post一对多关联
class User < ActiveRecord::Base
  has_many :posts   #请注意,这里使用复数
end
class Post < ActiveRecord::Base
  belongs_to :user     # foreign key - manager_id,并且user使用单数
end
over.




加载中
返回顶部
顶部