Search code examples
sqlruby-on-railsassociationsmodelshas-one

RAILS: has_one association based on non PK column


I have the following tables:

users 
  [id | name | type]

types
  [id | title]

I need to setup a has_one association ('users'.type => 'types'.id). But, as I understand, when I write something like:

user.rb

has_one :type

it seems to create a relation between 'users'.id and 'types'.id. How do I specify exactly 'users'.type => 'types'.id has_one association?


Solution

  • Finally found a solution:

    user.rb

    belongs_to :type
    

    type.rb

    has_many :users, foreign_key: "type_id"