简体   繁体   中英

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

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?

rails g migration add_user_to_questions user:references
rails db:migrate

Then in model:

class Question < ApplicationRecord # or ActiveRecord::Base
  belongs_to :author, class_name: 'User', foreign_key: :user_id
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM