user2572790 user2572790 - 2 months ago 9
SQL Question

Rails has_and_belongs_to_many with specific key

I has two models

class Fellow < ApplicationRecord
has_and_belongs_to_many :skills
end

class Skill < ApplicationRecord
has_and_belongs_to_many :fellows
end


One fellow can have some skills, and one skill can be learned by some fellows. So I have third table

class CreateFellowsSkills < ActiveRecord::Migration[5.0]
def change
create_table :fellows_skills, id:false do |t|
t.belongs_to :skill, index: true
t.belongs_to :fellow, index: true
end
end
end


I want to use method:
fellow.skills

That invoke such SQL:

SELECT "skills".* FROM "skills" INNER JOIN "fellows_skills" ON "skills"."id" = "fellows_skills"."skill_id" WHERE "fellows_skills"."fellow_id" = $1


The problem: I want to use field
skill_id
in table
skills
instead of
id
, so the query should be such:

SELECT "skills".* FROM "skills" INNER JOIN "fellows_skills" ON "skills"."skill_id" = "fellows_skills"."skill_id" WHERE "fellows_skills"."fellow_id" = $1


I tried to use different options in method
has_and_belongs_to_many
but the query is still incorrect.

Answer

http://cobwwweb.com/why-i-dont-use-has-and-belongs-to-many-in-rails

Instead of habtm, use

class Fellow < ApplicationRecord
  has_many :fellows_skills
  has_many :skills, through :fellows_skills
end

class Skill < ApplicationRecord
  has_many :fellows_skills
  has_many :fellows, through: :fellows_skills
end

class FellowsSkill < ApplicationRecord
  belongs_to :fellow
  belongs_to :skill
end

Furthermore I would suggest naming the third model FellowSkill (dropping the plural on fellow).