你總共需要3個表:用戶,項目和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
我得到了前兩個表,它是我對此感到困惑的第三個表。什麼:參考? foriegn關鍵? – TheWebs
請參閱[這裏](http://guides.rubyonrails.org/migrations.html#special_helpers)。 'model:references'基本上與'model_id:integer'相同,除非關係是多態的。所以,不,它不會添加外鍵(在這個時候);它唯一的優點是可讀性。 – PinnyM