首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >访问关联的关联

访问关联的关联
EN

Stack Overflow用户
提问于 2013-10-08 18:39:17
回答 1查看 72关注 0票数 2

我有一个Rails应用程序,它有一个用户模型,可以建立这样的朋友关系

User.rb

代码语言:javascript
复制
has_many :friendships
has_many :friends, :through => :friendships

每个用户都有一个has_many与Recipe.rb模型的关联。

在我的应用程序中,我想通过用户的朋友在用户展示页面上发布菜谱。即通过朋友协会获得朋友的食谱。因此,我在users_controller.rb中这样做

代码语言:javascript
复制
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

代码语言:javascript
复制
scope :recipes_by_friends, lambda { |friend_id|
  joins(:recipes).
  where(recipes: {user_id: friend_id})     
}

在“用户显示”页面中,我尝试显示每个菜谱。但是,在下面的代码中,菜谱局部变量实际上是朋友的活动记录关系,而不是朋友的菜谱。

/视图/用户/show.html.erb

代码语言:javascript
复制
<% @friend_recipes.each do |recipe| %></li> 
  <%= recipe.inspect %>  ## this is the relation for the user, not the recipe 
<% end %> 
  1. 我应该如何更改范围方法(或者更改其他方法?)在用户模型中得到菜谱?
  2. 这是循环遍历朋友并将他们的食谱添加到数组中的最佳方法吗? @user.friendships.each do朋友@friend_recipes << User.recipes_by_friends(friend.friend_id)结束
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-08 19:47:25

我相信,在这种情况下,你可以让ActiveRecord为你做这件事。

user.rb

代码语言:javascript
复制
has_many :friend_recipes, :through => :friends, :source => :recipes

users_controller.rb

代码语言:javascript
复制
def show 
  @friend_recipes = @user.friend_recipes 
end

由此生成的实际SQL查询将是:

代码语言:javascript
复制
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]]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19255679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档