我有一个Rails应用程序,它有一个用户模型,可以建立这样的朋友关系
User.rb
has_many :friendships
has_many :friends, :through => :friendships每个用户都有一个has_many与Recipe.rb模型的关联。
在我的应用程序中,我想通过用户的朋友在用户展示页面上发布菜谱。即通过朋友协会获得朋友的食谱。因此,我在users_controller.rb中这样做
def show
@friend_recipes = []
@user.friendships.each do |friendship|
@friend_recipes << User.recipes_by_friends(friendship.friend_id)
end
end调用用户模型上的类方法recipes_by_friends。
User.rb
scope :recipes_by_friends, lambda { |friend_id|
joins(:recipes).
where(recipes: {user_id: friend_id})
}在“用户显示”页面中,我尝试显示每个菜谱。但是,在下面的代码中,菜谱局部变量实际上是朋友的活动记录关系,而不是朋友的菜谱。
/视图/用户/show.html.erb
<% @friend_recipes.each do |recipe| %></li>
<%= recipe.inspect %> ## this is the relation for the user, not the recipe
<% end %> 发布于 2013-10-08 19:47:25
我相信,在这种情况下,你可以让ActiveRecord为你做这件事。
user.rb
has_many :friend_recipes, :through => :friends, :source => :recipesusers_controller.rb
def show
@friend_recipes = @user.friend_recipes
end由此生成的实际SQL查询将是:
2.0.0p247 :001 > user = User.first
2.0.0p247 :002 > user.friend_recipes
Recipe Load (1.7ms) SELECT "recipes".* FROM "recipes" INNER JOIN "friends" ON "recipes"."friend_id" = "friends"."id" INNER JOIN "friendships" ON "friends"."id" = "friendships"."friend_id" WHERE "friendships"."user_id" = ? [["user_id", 1]]https://stackoverflow.com/questions/19255679
复制相似问题