Reputation: 125
I have a User model having comment id as primary key. Now I have another model note. I want to add note_id in user model. I have changed my associations
Previous associations:
# user.rb
belongs_to :comment
# comment.rb
has_many :users, -> { order('users.display_date DESC') },
dependent: :destroy, inverse_of: :comment
Current associations:
# user.rb
belongs_to :note, optional: true
# note.rb
has_many :users, -> { order('users.display_date DESC') },
dependent: :destroy
I have added records in user model and inserting note_id. But fetching records in console showing nil value.
User.last.note
=> nil
Could someone help me where I am missing in associations?
Upvotes: 0
Views: 64
Reputation: 1725
As pointed out in comment section, something doesn't "feel right" in your association model.
You can "feel it" just by reading out loud user belongs to comment
instead of User has many Comments
or Comment belongs to User
.
I am not sure if you are adding the notes model to your existing system or you switching from comments to notes, but please mind something doesn't seem okay!
# `users` table has no reference to comments
class User < ApplicationRecord
has_many :comments, dependent: :destroy
end
# `comments` table should have a `user_id` column
class Comment < ApplicationRecord
belongs_to :user
end
If you want just one note per user
, I'd recommend:
# `users` table has no reference to notes
class User < ApplicationRecord
has_one :note
end
# `notes` table should have a `user_id` column
class Note < ApplicationRecord
belongs_to :user
end
Please let me know if it worked :)
Upvotes: 1