Understanding Rails Model Relationships

Asked 1 years ago, Updated 1 years ago, 81 views

Let's talk about the following models.

  • id
  • title
  • id
  • name

I would like to add created_user_id and updated_user_id to Post. What should I do?

If you want to add user_id,
raid migration AddUserIdToPost user_id:references would be good.

raildg migration AddCreatedUserIdToPost created_user_id:references would be associated with a model called CreatedUser, right?

created_user_id and updated_user_idHow do I associate both with User

?

ruby-on-rails rails-activerecord

2022-09-30 16:33

1 Answers

There seems to be no way to accomplish this with just one migration, so

 railsg migration AddCreatedUserIdToPosts created_user_id: integer
railsg migration AddUpdatedUserIdToPosts updated_user_id — integer

After adding the integer column as the , you will be writing it to the model.

class Post<ActiveRecord::Base
  belongs_to:created_user,:class_name=>User
  belongs_to:updated_user,:class_name=>User
end

I think it would be better to write it down on the user as well.

class User<ActiveRecord::Base
  has_many:created_posts,:class_name=>Post,:foreign_key=>:created_user_id
  has_many:updated_posts,:class_name=>Post,:foreign_key=>:updated_user_id
end

Active Record associations are detailed in http://railsguides.jp/association_basics.html.


2022-09-30 16:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.