如何实现应返回技能的方法

时间:2018-06-07 14:28:17

标签: ruby-on-rails ruby

我无法理解如何实现primary_skill方法。此方法应返回标记为主要的技能 user.primary_skill

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

class Skill < ApplicationRecord
  validates :title, presence: true, uniqueness: true

  has_many :user_skills
  has_many :users, through: :user_skills
end

class UserSkill < ApplicationRecord
  belongs_to :skill
  belongs_to :user
end

create_table "user_skills", force: :cascade do |t|
  t.boolean "primary", default: false
  t.bigint "skill_id"
  t.bigint "user_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.index ["skill_id"], name: "index_user_skills_on_skill_id"
  t.index ["user_id"], name: "index_user_skills_on_user_id"
end

1 个答案:

答案 0 :(得分:3)

@Alec的答案几乎肯定会导致语法错误,该块无法在逻辑上评估该表达式。

您可以通过以下方式实现这一目标:

class User < ApplicationRecord
  has_many :user_skills
  has_many :skills, through: :user_skills
  has_many :primary_user_skills, -> { where(primary: true) }, class_name: 'UserSkill'
  # Above cannot be has_one, we are creating intermediate relationship from user_skills where primary is true.

  def primary_skill
    primary_user_skills.first.try(:skill)
  end
end

编辑 - 简化版同样可以在下面:

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

  def primary_skill
    skills.find_by(user_skills: {primary: true})
  end
end