【问题标题】:How to print my posts and posts of my friends?如何打印我的帖子和我朋友的帖子?
【发布时间】:2013-07-03 11:55:55
【问题描述】:

我有 2 个模型,userfriendship,它们的外观如下:

class User < ActiveRecord::Base
  has_many :posts
  has_many :friendships, :conditions => { :confirmed => true }
  has_many :friend_requests, :class_name => 'Friendship', :conditions => { :confirmed => false }
  has_many :friends, :through => :friendships
  has_many :friends_friendships, :through => :friends, :source => :friendships
  has_many :friends_of_friends, :through => :friends_friendships, :source => :friend
  has_many :friends_listings, :through => :friends, :source => :listings
  has_many :friends_posts, :through => :friends, :source => :posts
  ...
end

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User"
  attr_accessible :friend_id
  ...
end

这是我获取当前登录用户的帖子和他/她朋友的帖子的方法:

  @my_posts = current_user.posts.includes(:user)
  @friends_posts = current_user.friends_posts.includes(:user)

这很好用,但是如何将我的帖子和朋友的帖子加载到一个变量中并像在 Facebook 上一样显示它们?换句话说,我怎样才能将这 2 个查询合并为一个?

谢谢

【问题讨论】:

  • 我写了一个 SQL 来实现。

标签: ruby-on-rails ruby activerecord model associations


【解决方案1】:

类似这样的:

ids = current_user.friends.pluck(:id) << current_user.id
posts = Post.where(user_id: ids)

返回

SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1, 2, 3, 6)

然后在视图中:

posts.each do |post|
  ....
end

【讨论】:

  • 您好,感谢您的努力,我正在尝试此操作,但无法克服此错误消息:SQLite3::SQLException: ambiguous column name: id: SELECT id FROM "users" INNER JOIN "friendships" ON "users"."id" = "friendships"."friend_id" WHERE "friendships"."user_id" = 2 AND "friendships"."confirmed" = 't' - 怎么了?
  • current_user.friends 会返回一组与 current 成为朋友的用户,对吧?它应该和你有user has many friends 关系一样。
  • 你可以尝试这种方式ids = current_user.friends.map{|f| f.id} &lt;&lt; current_user.id,它也会返回一个id数组,包括你自己的,看看它是否有效。可能是采摘方法不适合你。
猜你喜欢
  • 2019-01-12
  • 1970-01-01
  • 2013-11-21
  • 2014-01-19
  • 1970-01-01
  • 2012-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多