迁移has_one和has_many

时间:2016-02-17 19:54:39

标签: ruby-on-rails ruby postgresql migration database-migration

class Post < ActiveRecord::Base
  has_one :owner, class_name: "User", foreign_key: "owner_id" #creator post
  has_many :users #followers post
end

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

 has_many :posts 
 end

我需要执行哪些命令行来迁移以在User表和Post表之间执行这些不同的关系?  感谢

1 个答案:

答案 0 :(得分:1)

Post belong_to :owner,因为posts表具有外键。此外,#users的{​​{1}}有点过于模糊,而User#posts也是如此。

以下是您的模特:

class Post < ActiveRecord::Base
  belongs_to :owner, class_name: 'User', inverse_of: :owned_posts # foreign_key: :owner_id will be inferred
  has_many :subscriptions
  has_many :followers, through: :subscriptions, source: :user, class_name: 'User', inverse_of: :followed_posts
end

class Subscription < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :owned_posts, class_name: 'Post', inverse_of: :owner
  has_many :subscriptions
  has_many :followed_posts, through: :subscriptions, source: :post, class_name: 'Post', inverse_of: :followers
end

以下是支持他们的迁移:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      # ...
    end
  end
end

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.integer :owner_id
      # ...
    end
  end
end

class CreateSubscriptions < ActiveRecord::Migration
  def change
    create_table :subscriptions do |t|
      t.integer :post_id
      t.integer :user_id
    end
  end
end

如果不是'所有权'关系,,您可以使用has_and_belongs_to_many关系:

  1. subscriptions迁移重命名为posts_users(必须按字母顺序复数),
  2. 完全取消其模型,
  3. Post.has_and_belongs_to_many :usersUser.has_and_belongs_to_many :posts
  4. 事实上,你在技术上可以这样做,但是这样的模糊名称是不好的做法。