Give composite primary key in Rails

独自空忆成欢 提交于 2019-12-01 10:52:55

It looks like you're trying to specify a many-many relationship between Users and Projects, with an additional field on the relationship itself.

The way you're currently doing isn't the Rails way of doing things - especially with the concept of a composite primary key.

The Rails/ActiveRecord way of doing this sort of relationship modelling is to have a third model that describes the relationship between User and Project. For the sake of example, I'm going to call it an Assignment. All you need to do is re-name your user_has_projects table to assignments like so:

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

And then, in your model files:

# 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

You can read more about this here: http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!