Ruby on rails 如何实现应该返回技能的方法

Ruby on rails 如何实现应该返回技能的方法,ruby-on-rails,ruby,Ruby On Rails,Ruby,我无法理解如何实现基本技能方法。此方法应返回标记为主要的技能 用户基本技能 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_s

我无法理解如何实现基本技能方法。此方法应返回标记为主要的技能 用户基本技能

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
class用户
由@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用户{where(primary:true)},类名:'UserSkill'
#以上不可能有一个,我们正在从用户技能创建中间关系,其中主要是真的。
基本技能
主要用户技能。首先。尝试(:技能)
结束
结束
编辑-简化版可在下面找到:

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
class用户
您当前的设置允许将多种技能标记为
主要技能
。您应该为该属性添加唯一性验证/约束。您能解释一下为什么您认为我的答案会导致语法错误吗?我在一个应用程序中使用了一些几乎相同的东西,虽然它在最新日期而不是布尔值上求值,但工作正常。嗨@AlecSanger,lambda是在运行时求值的,你在lambda中有
class\u name
,这是错误的,它应该在lambda之外。而且,当中间关系为collection@kiddorails非常感谢你!你帮了我很多@AlecSanger感谢您的帮助,您的回答导致了语法错误