Ruby on rails 正在为此关系创建迁移
一夜之间,我完全忘记了如何为这种类型的关系创建迁移: 我有一个项目表和一个用户表,每个用户都有自己创建的项目,用户可以在项目中创建或编辑时共享他们创建的项目,因此关系为: 每个项目可能有许多用户并属于用户,而每个用户有许多项目并属于一个项目 问题出在哪里 我不知道如何从此>>进行迁移,因为有人告诉我需要创建一个新表来规定这种关系 我在想Ruby on rails 正在为此关系创建迁移,ruby-on-rails,ruby,ruby-on-rails-3,migration,relationship,Ruby On Rails,Ruby,Ruby On Rails 3,Migration,Relationship,一夜之间,我完全忘记了如何为这种类型的关系创建迁移: 我有一个项目表和一个用户表,每个用户都有自己创建的项目,用户可以在项目中创建或编辑时共享他们创建的项目,因此关系为: 每个项目可能有许多用户并属于用户,而每个用户有许多项目并属于一个项目 问题出在哪里 我不知道如何从此>>进行迁移,因为有人告诉我需要创建一个新表来规定这种关系 我在想 generate migration project_user project_id :int user_id :int 这是正确的吗?您总共需要3个表:用户
generate migration project_user project_id :int user_id :int
这是正确的吗?您总共需要3个表:用户、项目和项目编辑器链接 您的迁移:
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
您总共需要3个表:用户、项目和项目编辑器链接 您的迁移:
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
我拿到了前两张桌子,这是我感到困惑的第三张。什么:推荐信?外国钥匙?看。model:references与model_id:integer基本相同,除非关系是多态的。因此,不,此时不会添加外键;它唯一的优点是可读性。我得到了前两张表,这是我感到困惑的第三张表。什么:推荐信?外国钥匙?看。model:references与model_id:integer基本相同,除非关系是多态的。因此,不,此时不会添加外键;它唯一的优点是可读性。