我有一个 Rails 应用程序,其用户模型可以像这样设置 friend 关系
用户.rb
has_many :friendships
has_many :friends, :through => :friendships
每个用户都与 Recipe.rb 模型有一个 has_many
关联
在我的应用程序中,我想在用户的显示页面上发布该用户的 friend 的食谱。即通过 friend 协会获取 friend 的食谱。因此,我在 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
用户.rb
scope :recipes_by_friends, lambda { |friend_id|
joins(:recipes).
where(recipes: {user_id: friend_id})
}
在用户显示页面中,我尝试显示每个食谱。然而,在下面的代码中,菜谱局部变量实际上是 friend 的事件记录关系,而不是 friend 的菜谱。
/views/users/show.html.erb
<% @friend_recipes.each do |recipe| %></li>
<%= recipe.inspect %> ## this is the relation for the user, not the recipe
<% end %>
我应该如何更改用户模型中的范围方法(或更改其他内容?)来获取食谱?
这是循环遍历 friend 并将他们的食谱添加到数组的最佳方式吗?
@user.friendships.each do |friend| @friend_recipes << User.recipes_by_friends(friend.friend_id) end
最佳答案
我相信在这种情况下您可以让 ActiveRecord 为您完成繁重的工作。
用户.rb
has_many :friend_recipes, :through => :friends, :source => :recipes
users_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]]
关于ruby-on-rails - 访问关联的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19255679/