Rails-api:从第二个连接表关联元数据



我有,在高层,Recipe, SkillUser,与RecipeSkillUserSkill的连接表。

当返回给定食谱的技能时,我想知道用户已经学习了该食谱的哪些技能。你可以在下面看到一些JSON示例。

我甚至不确定这个问题的最好表达方式,因为我只是对如何解决这个问题感到困惑。我相信我可以把一些东西拼凑在一起,但这似乎是一个相当常见的情况,必须有一些预先存在的约定。

这是我的模型和我的RecipeSerializer:

class Recipe < ActiveRecord::Base
  has_many :recipe_skills
  has_many :skills, through: :recipe_skills
end
class Skill < ActiveRecord::Base
  has_many :recipe_skills
  has_many :recipes, through: :recipe_skills
end
class RecipeSkill < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :skill
end
class User < ActiveRecord::Base
  has_many :user_skills
  has_many :skills, through: :user_skills
end
class UserSkill < ActiveRecord::Base
  belongs_to :user
  belongs_to :skill
  # attributes :id, :user_id, :skill_id, :strength, :capacity, :learned
end
class RecipeSerializer < ActiveModel::Serializer
  embed :ids, include: true
  has_many :skills
  attributes :id, :title
end

这里有一些JSON示例:

{
  "skills": [
    {
      "id": 1,
      "name": "Grilling Chicken",
      "earned": true
    }
  ]
  "recipe": {
    "id": 1,
    "title": "Roasted Potatoes",
    "skill_ids": [
      1
    ]
  }
}

Skill序列化器上,也许可以添加一个方法来确定用户是否具有该技能。假设user.skills包含他们学过的技能:

class SkillSerializer < ActiveModel::Serializer
  attributes :earned, # :id, :name, etc
  def earned
    scope.skills.include? object  
  end
end

Scope是你所代表的用户。参考这里的文档

我认为这里可能存在一些性能问题,但希望它能使您朝着正确的方向前进。