Let's talk about the following models.
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_id
How do I associate both with User
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.
© 2024 OneMinuteCode. All rights reserved.