Rails 5: Add belongs_to association with custom name to model, and migration
Asked Answered
N

1

22

I have a User model and a Question model.

I want to add a belongs_to :user association to the Question model, but I want that association to be called author. For example, I would call question.author rather than question.user.

Obviously this requires two steps:

  1. The association in the models/question.rb
  2. The migration (note both the user and question tables already exist)

Surprisingly I haven't found the single, conventional method of doing this in Rails 5 in a different answer.

How do I do this?

Neve answered 2/11, 2016 at 8:15 Comment(0)
M
24
rails g migration add_user_to_questions user:references
rails db:migrate

Ideally, you also open the generated migration and change the add_reference by adding options which you need. Example of more "full" add_reference:

add_references(
  :user,
  null: false,
  index: {name: "custom_index_name_if_needed"},
  type: :integer,
  foreign_key: {
    to_table: "public.my_users_table",
    on_delete: :cascade # ensure the row is deleted when user is deleted from DB
  }
)

Then in model:

class Question < ApplicationRecord # or ActiveRecord::Base
  belongs_to :author, class_name: 'User', foreign_key: :user_id
end
Morrissey answered 2/11, 2016 at 8:17 Comment(3)
Beautiful, thanks! One more question.. how come sometimes we use bin/rails ..., rails ..., and rake ...?Neve
@Neve sorry, starting from rails 5 both should be rails - they changed itMorrissey
it will create add_reference :questions, :user, foreign_key: true in migration's file.Flessel

© 2022 - 2024 — McMap. All rights reserved.