我有两个班级的工作和一个技能,他们之间有两个关系
这些是我的课程
class Job < ActiveRecord::Base
has_many required, class_name: 'Skill', :through => JobSkill
has_many nice_to_have, class_name: 'Skill', :through => JobSkill
end
class Skill < ActiveRecord::Base
has_many :jobs
end
但我错过了它们之间的连接器。
class JobSkill < ActiveRecord::Base
belongs_to :skill
belongs_to :required, class_name 'Job',
belongs_to :nice_to_hace, class_name 'Job'
end
作为表格我会:
create_table :jobs do |t|
t.string :job_identifier
t.references :requirement
t.references :nice_to_have
end
create_table :skills do |t|
t.string :name
end
create_table :job_skills do |t|
t.references :requirement
t.references :nice_to_have
t.integer :skill_id
end
这是正确的表示吗?因为查看模型我不确定我是否拥有所有连接
引用是否足以连接所有表或我是否需要使用:foreign_key在连接中?
答案 0 :(得分:2)
我想我会这样做
class Job < ActiveRecord::Base
has_many :job_skills
has_many :skills, :through => :job_skills
end
class JobSkill < ActiveRecord::Base
belongs_to :job
belongs_to :skill
# add boolean attribute :required
end
class Skill < ActiveRecord::Base
has_many :job_skills
has_many :jobs, :through => :job_skills
end
通过这种方式,您可以添加技能,然后决定他们是否适合拥有或需要。
create_table :jobs do |t|
t.string :job_identifier
end
create_table :skills do |t|
t.string :name
end
create_table :job_skills do |t|
t.references :job
t.references :skill
t.boolean :required, default: false, null: false
end
而且,为了获得这项工作的优秀或必需的技能,你可以添加这个has_many
class Job < ActiveRecord::Base
has_many :job_skills
has_many :skills, :through => :job_skills
has_many :required_skills, -> { where job_skills: { required: true } }, through: :job_skills, class_name: 'Skill', source: :skill
has_many :nice_to_have_skills, -> { where job_skills: { required: false } }, through: :job_skills, class_name: 'Skill', source: :skill
end