0

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.

user2572790
  • 442
  • 3
  • 13
  • 1
    `skill_id` is this a column you have added to `skills` table ? – dp7 Sep 16 '16 at 06:51
  • Yes, I have primary key ID in table SKILLS, but while FELLOW.SKILLS, I need to use field SKILL_ID – user2572790 Sep 16 '16 at 06:54
  • 1
    You can do this by using foreign_key as `skill_id`. Check this: http://stackoverflow.com/questions/1475088/how-can-i-load-habtm-with-foreign-key-relationships-in-my-fixtures – Gokul Sep 16 '16 at 06:54

2 Answers2

1

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

Dan Andreasson
  • 15,380
  • 5
  • 29
  • 30
0

Finally I correct my db scheme and call primary key ID, so I don't need apply any changes now.

user2572790
  • 442
  • 3
  • 13