1

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

1 Answer 1

1

This is how you should define the model associations.

class UserType < ApplicationRecord
  has_many :users
end

class User < ApplicationRecord
  belongs_to :user_type
end

You should read once this association_basics guide to understand how associations works in Rails.

3
  • Thanks for the help, but this one if I type user.user_type = 1 it will return UserType expected, got 1 which is an instance of integer how do I solve this?
    – John Nuno
    Sep 16, 2018 at 7:12
  • user.user_type_id = 1 you need to do, else user.user_type = <it should be a UserType> object. add_reference method added a user_type_id column to the users table, check the schema.rb file. Sep 16, 2018 at 7:21
  • 1
    @JohnNuno One thing I'd say here is that, it makes sense more UserRole, not UserType IMO :) Sep 16, 2018 at 7:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.