【问题标题】:creating a migration for this relationship为此关系创建迁移
【发布时间】:2012-11-21 21:26:31
【问题描述】:

一夜之间我完全忘记了如何为这种类型的关系创建迁移:

我有一个项目表和一个用户表,每个用户都有自己创建的项目,用户如何在创建或编辑项目时共享他们创建的项目,所以关系是:

每个项目可能有很多用户,属于用户,每个用户有很多项目,属于一个项目。

问题?

我不知道如何从中进行迁移 >.> 有人告诉我我需要创建一个新表来规定这种关系。

我在想

generate migration project_user project_id :int user_id :int

这是对的吗?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 migration relationship


    【解决方案1】:

    你一共需要3个表:users、projects和project_editor_links

    您的迁移:

    create_table :users do |t|
      # user stuff
    end
    
    create_table :projects do |t|
      t.references :user
      # project stuff
    end
    
    create_table :project_editor_links |t|
      t.references :user
      t.references :project
    end    
    

    从命令行生成最后一个表:

    rails g migration project_editor_links project:references user:references
    

    您的模型应如下所示:

    class User < ActiveRecord::Base
      has_many :projects
      has_many :project_editor_links
      has_many :edited_projects, :through => :project_editor_links
    end
    
    class Project < ActiveRecord::Base
      belongs_to :user
      has_many :project_editor_links
      has_many :editors, :through => :project_editor_links
    end
    
    class ProjectEditorLinks < ActiveRecord::Base
      belongs_to :editor, :class_name => 'User', :foreign_key => :user_id
      belongs_to :edited_project, :class_name => 'Project', :foreign_key => :project_id
    end
    

    【讨论】:

    • 我得到了前两个表,第三个我很困惑。什么:参考?外键?
    • heremodel:referencesmodel_id:integer 基本相同,除非关系是多态的。所以,不,它不会添加外键(此时);它唯一的优点是可读性。
    猜你喜欢
    • 2020-04-13
    • 2020-05-08
    • 2020-12-16
    • 2021-07-12
    • 2021-04-15
    • 2019-03-22
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多