Rails one-to-one relationship

后端 未结 3 1237
攒了一身酷
攒了一身酷 2021-02-02 02:29

I have the following:

class User < ActiveRecord::Base
  has_one :car, :class_name => \'Car\', :foreign_key => \'user_id\'

class Car < ActiveRecord::         


        
3条回答
  •  一向
    一向 (楼主)
    2021-02-02 02:43

    Change the definition of the relationship slightly:

    class User < ActiveRecord::Base
      has_one :car
    
    class Car < ActiveRecord::Base
      belongs_to :worker, :class_name => 'User', :foreign_key => 'user_id'
    

    And you'll establish what you're looking for. See: http://guides.rubyonrails.org/association_basics.html#the-has-one-association

提交回复
热议问题