我在Recipe
,Skill
和User
的高级别,RecipeSkill
和UserSkill
的联接表。
当返回给定食谱的技能时,我想知道用户已经学习的食谱的技能。您可以在下面看到一些示例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
]
}
}
答案 0 :(得分:1)
在Skill
序列化程序上,或许添加一个方法来确定用户是否具备该技能。假设user.skills
包含他们所学到的技能:
class SkillSerializer < ActiveModel::Serializer
attributes :earned, # :id, :name, etc
def earned
scope.skills.include? object
end
end
范围是您代表的用户。请参阅docs here。
我认为这里可能存在一些性能问题,但希望它可以帮助您找到正确的方向。