0

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?

2
  • Have you rename comment_id column to note_id? Commented Dec 25, 2022 at 3:39
  • 1
    The model is hard to understand, just to be sure... you are having multiple users per comment/note but users can only be part of [0..1] notes? Usually User has_many notes and notes belongs_to user. Or maybe its an N-to-N relation. This is just and observation I have no further knowledge of your model. Commented Dec 26, 2022 at 4:16

1 Answer 1

1

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!

Let's fix the "User-Comment" relation problem first

# `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 

Let's fix the "User-Note" relation problem

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.