如何在没有任何宝石的情况下在Rails中提供复合主键?
迁移文件中的第一个表:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :userid
t.string :name
t.string :address
t.timestamps
end
end
def self.down
drop_table :users
end
end
迁移文件中的第二个表:
class CreateProjects < ActiveRecord::Migration
def self.up
create_table :projects do |t|
t.string :title
t.string :description
t.timestamps
end
end
def self.down
drop_table :projects
end
end
在我的架构文件中:
ActiveRecord::Schema.define(:version => 20110222044146) do
create_table "projects", :force => true do |t|
t.string "title"
t.string "description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", :force => true do |t|
t.string "userid"
t.string "name"
t.string "address"
t.datetime "created_at"
t.datetime "updated_at"
end
end
现在我想创建一个名为User_has_project
的表,在其中我将引用User和Project,这意味着将有2个外键。
所以我试着这样:
class CreateUser_has_projects < ActiveRecord::Migration
def self.up
create_table :user_has_projects do |t|
t.references :User
t.references :Project
t.boolean :status
t.timestamps
end
end
def self.down
drop_table :users
end
end
现在如何在user_has_projects中将user_id和project_id的组合设置为主键?
答案 0 :(得分:2)
您似乎试图在Users
和Projects
之间指定多对多的关系,并在关系本身上添加一个字段。
您目前的做法不是Rails的做事方式 - 特别是使用复合主键的概念。
执行此类关系建模的Rails / ActiveRecord方法是使用第三个模型来描述User
和Project
之间的关系。为了举例,我将其称为Assignment
。您需要做的就是将user_has_projects
表重新命名为assignments
,如下所示:
class CreateAssignments < ActiveRecord::Migration
def self.up
create_table :assignments do |t|
t.references :user
t.references :project
t.boolean :status
t.timestamps
end
end
def self.down
drop_table :assignments
end
end
然后,在您的模型文件中:
# app/models/user.rb
class User < ActiveRecord::Base
has_many :assignments
has_many :projects, :through => :assignments
end
# app/models/assignment.rb
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
# app/models/project.rb
class Project < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments
end
您可以在此处详细了解:http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association