Give composite primary key in Rails

前端 未结 1 773
小蘑菇
小蘑菇 2021-01-15 15:02

How can i give composite primary key in Rails without any gem?

My first table in migration file:

class CreateUsers < Act         


        
相关标签:
1条回答
  • 2021-01-15 15:25

    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

    0 讨论(0)
提交回复
热议问题