简体   繁体   中英

Foreign keys in rails model generation

Is there a way to generate a model in rails that contains foreign keys with cascading delete? I want to have a model "game" that has two users attached to it based on the two users playing. How do I create those two users as foreign user objects so they will a) load when I load the game object, and b) automatically be deleted if one of the users is deleted?

Something like this maybe:

User model:

class User < ActiveRecord::Base
  has_many :games, :dependent => :destroy
end

And your game model:

class Game < ActiveRecord::Base
  belongs_to :user1, :class_name => "User", :foreign_key => "user1_id"
  belongs_to :user2, :class_name => "User", :foreign_key => "user2_id"
end

If you want to use database foreign keys you can use:

https://github.com/matthuhiggins/foreigner

use is like:

add_foreign_key(:games, :users, :column => 'user1_id', :dependent => :delete)
add_foreign_key(:games, :users, :column => 'user2_id', :dependent => :delete)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM