Kumar Nikhil
Kumar Nikhil

Reputation: 125

Rails model associations

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

Answers (1)

ASX
ASX

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!

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

Upvotes: 1

Related Questions