首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >迁移has_one和has_many

迁移has_one和has_many
EN

Stack Overflow用户
提问于 2016-02-17 19:54:39
回答 1查看 820关注 0票数 0
代码语言:javascript
复制
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

为了在用户表和Post表之间执行这些不同的关系,我需要执行哪些命令行来迁移?谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-17 21:55:44

belong_to:owner,应该是Post,因为posts表有外键。而且,它的#usersUser#posts的名字有点太模糊了。

这是你们的模特:

代码语言:javascript
复制
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

以下是支持他们的迁徙:

代码语言:javascript
复制
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

实际上,从技术上讲,您可以做到这一点,但是使用这样的模糊名称是一种糟糕的做法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35466451

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档