1

在高层次上,我有 ,RecipeSkill,与和User的连接表。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
    ]
  }
}
4

1 回答 1

1

也许,在Skill序列化程序上,添加一个方法来判断用户是否具有该技能。假设如果user.skills包含他们学到的技能:

class SkillSerializer < ActiveModel::Serializer

  attributes :earned, # :id, :name, etc

  def earned
    scope.skills.include? object  
  end
end

范围是您所代表的用户。请参阅此处的文档

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

于 2014-06-18T22:53:03.117 回答