我有两个模型用户和食谱。用户可以创建配方,用户可以将配方添加到收藏夹。
在rails中,我在User模型中使用Favorites模型(user_id,recipe_id)进行了这样的关联。 我已经有了最喜欢的用户食谱。我怎样才能获得当前用户创建的食谱?
has_many :favorites
has_many :recipes
has_many :recipesbox, through: :favorites, source: :recipe
当我在Ember js尝试制作时,我遇到了麻烦。
user_serializer.rb
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :email
has_many :recipes, embed: :ids
has_many :recipesbox, through: :favorites, embed: :ids
end
user.js.coffee
App.User = DS.Model.extend
name: DS.attr('string')
email: DS.attr('string')
recipes: DS.hasMany('App.Recipe')
recipe.js.coffee
App.Recipe = DS.Model.extend
user: DS.belongsTo('App.User')
title: DS.attr('string')
user.hbs
<h1>{{name}}</h1>
<p><b>Email:</b> {{email}}</p>
<h3>Favorites</h3>
{{#each recipe in recipes}}
<div>
<span>{{recipe.id}}</span>
<span>{{recipe.title}}</span>
</div>
{{/each}}
我的序列化用户是:
{
user: {
id: 1,
name: "ejiqpep",
email: "ejiqpep@gmail.com",
recipe_ids: [
4,
5
],
recipesbox_ids: [
4,
1,
2,
3
]
}
}
答案 0 :(得分:0)
怎么样
App.User = DS.Model.extend
name: DS.attr('string')
email: DS.attr('string')
recipes: DS.hasMany('App.Recipe')
favorites: DS.hasMany('App.Favorite')
然后分别是模型
App.Favorite = DS.Model.extend({..});