Rails Association and migration

2428 views ruby-on-rails
5

If I wanted to have a "user_type" column in my "users" table that references to another table called "user_type", how do I write the correct association in rails? For example if my user_type is 1 and 1 is admin in my user_types table, and when I write this in my rails console

user = User.first
user.user_type #I want this to return admin

I've tried with

class AddTypeToUsers < ActiveRecord::Migration[5.2]
  def change
    add_reference :users, :user_type, foreign_key: true
  end
end

But it won't work

thank you in advance

answered question

1 Answer

11

This is how you should define the model associations.

class UserType < AR
  has_many :users
end

class User < AR
  belongs_to :user_type
end

posted this

Have an answer?

JD

Please login first before posting an answer.