ruby-on-rails - 访问关联的关联

标签 ruby-on-rails

我有一个 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 %> 
  1. 我应该如何更改用户模型中的范围方法(或更改其他内容?)来获取食谱?

  2. 这是循环遍历 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/

相关文章:

ruby-on-rails - 尝试关注一本书,但没有生成我的表格,这是为什么?

ruby-on-rails - 当powershell处于 'select'模式时,如何停止服务器卡住?

ruby-on-rails - rails 在获取所有请求中包含所有关联数据

ruby-on-rails - Cucumber BDD for RAILS/ActiveRecord - 通过填充数据库层来加速慢速测试?

javascript - Ajax 追加问题

ruby-on-rails - 嵌套资源的参数名称是什么

ruby-on-rails - 安装 Rails 3 时如何修复 (Errno::EINVAL) 错误?

ruby-on-rails - 推送到 heroku 时,rake 中止不接受 TCP/IP 连接

ruby-on-rails - 从数组的数组中删除重复项

ruby-on-rails - 将 Ruby .map 的结果附加到数组中?