Search code examples
rubypostgresqlactiverecordrelationshipruby-on-rails-6

How to get id from associated relation rails?


Can i get an id from associated relation? for example i have relation between user and skill through user_skill

In User model, i write like this:

class User < ApplicationRecord
  has_many ::skills, through: :user_skills
end

In UserSkill model

class UserSkill < ApplicationRecord
  belongs_to :skill
  belongs_to :user
end

I can call them like this

User.find(1).skills

but there is no user_skill id in there. how to include id of user_skill? because everytime i call

User.find(1).skills

it will be like this

[#<Skill id: 3, name: "Google Analytics", description: "Google Analytics\r\n", created_at: "1970-01-04 11:20:00.000000000 +0000", updated_at: "1970-01-04 11:20:00.000000000 +0000", category: "software">, #<Skill id: 8, name: "Adobe After Effect", description: "Test", created_at: "2022-08-21 02:58:25.561498000 +0000", updated_at: "2022-08-21 02:58:25.561498000 +0000", category: "software">, #<Skill id: 1, name: "Microsoft Office", description: "Word, Excel, PowerPoint", created_at: "1970-01-02 03:46:40.000000000 +0000", updated_at: "1970-01-02 03:46:40.000000000 +0000", category: "software">]

Solution

  • You can do:

    user_skills = User.find(1).user_skills.include(:skill)
    
    user_skills.each do |user_skill|
      user_skill.id      #=> the user_skill id
      user_skill.skill   #=> the actual skill
    end