【问题标题】:Rails: Why can't I run .paginate on current_user.friends?Rails:为什么我不能在 current_user.friends 上运行 .paginate?
【发布时间】:2012-09-19 14:38:58
【问题描述】:

我正在使用 Amistad gem 创建好友系统。它包括一个友谊模型和控制器,我假设它们以各种方式与我的用户模型相关联:通过方式等,并且到目前为止所有功能似乎都可以工作。

在视图中循环通过 current_user.friends 可以提供用户的朋友,并允许您访问所有普通用户字段。例如.email、.name 等。

现在我想分页并将 search_for 应用于 current_user.friends,就像我通常在我的用户模型上所做的那样,但它不起作用。

所以,这行得通:

User.order('created_at desc').search_for(params[:search]).paginate(per_page: 10, page: params[:page])

但是这个

current_user.friends.search_for(params[:search]).paginate(per_page: 10, page: params[:page])

给予

NoMethodError (undefined method `search_for' for #<Array:0x007faac0b0db10>):

或者这个,当我敲掉 search_for 时

NoMethodError (undefined method `paginate' for #<Array:0x007faac015c7d8>):

希望这里有一个简单的答案!

编辑也许我可以通过 User.where(current_user.friends) 或其他方式解决这个问题?

【问题讨论】:

    标签: ruby-on-rails model pagination associations


    【解决方案1】:

    User.order... 返回一个 ActiveRelation 对象,current_user.friends 返回一个数组。 试试这个。

    User.joins('INNER JOIN friendships ON friendships.friend_id = users.id').where(:friendships => {:user_id => current_user.id, :pending => false, :blocker_id => nil})
    

    【讨论】:

    • 谢谢。你知道是否可以获取 current_user.friends 的 ActiveRelation 对象吗?
    • 我认为你必须通过友谊,像这样: User.joins(:friendships).where(:friendships => {:friendable_id => current_user.id}) 也许它是一个 :friend_id而不是 :friendable_id
    • 似乎几乎可以工作 - 不再有错误,我只是没有得到任何物品, User.joins(:friendships).where(:friendships => {:friend_id => current_user.id})
    • 检查你的数据库,看看里面有什么数据,对于哪个用户,也许这个用户没有友谊记录?还可以尝试运行 AR 生成的查询,看看您是否可以在 Sequel Pro 等数据库中手动运行它。
    • 在 current_user.friends 中肯定有 4 个朋友。我刚刚查看了 SQL 查询 - 它的“SELECT COUNT(*) FROM "users" INNER JOIN "friendships" ON "friendships"."user_id" = "users"."id" WHERE "friendships"."friend_id" = 1 " - 有趣 - 我的用户的 ID 为 1 - 我不是在寻找friend_id = 1 的位置?
    猜你喜欢
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    相关资源
    最近更新 更多