如何从current_user.friends + limit获取状态到10个状态

时间:2011-07-19 19:05:34

标签: ruby-on-rails ruby ruby-on-rails-3

这是我的代码:

@current_user_statuses = current_user.statuses.limit(10)

@friends_statuses = current_user.friends.collect(&:statuses) 

if current_user.friends.collect(&:doweets)[0].any? 
  @friends_statuses = current_user.friends.collect(&:statuses)[0]
end

@statuses = (@current_user_statuses + @friends_statuses).sort_by{ |d| - d.created_at.to_i

我想这样做:

@current_user_statuses = current_user.statuses.limit(10)

@friends_statuses = current_user.friends.statuses.limit(10)    

@statuses = (@current_user_statuses + @friends_statuses).sort_by{ |d| - d.created_at.to_i

但是当我这样做时,我得到一个错误......

我该怎么做?

我的模特:

友谊模特:

    belongs_to :user
belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"

def self.are_friends(user, friend)
  return false if user == friend
  return true unless find_by_user_id_and_friend_id(user, friend).nil?
  return true unless find_by_user_id_and_friend_id(friend, user).nil?
  return false
end

def self.request(user, friend)
  return false if are_friends(user, friend)
  return false if user == friend
  f1 = new(:user => user, :friend => friend, :status => "pending")
  f2 = new(:user => friend, :friend => user, :status => "requested")
  transaction do
    f1.save
    f2.save
  end
end

def self.accept(user, friend)
  f1 = find_by_user_id_and_friend_id(user, friend)
  f2 = find_by_user_id_and_friend_id(friend, user)
  if f1.nil? or f2.nil?
    return false
  else
    transaction do
      f1.update_attributes(:status => "accepted")
      f2.update_attributes(:status => "accepted")
    end
  end
  return true
end

def self.reject(user, friend)
  f1 = find_by_user_id_and_friend_id(user, friend)
  f2 = find_by_user_id_and_friend_id(friend, user)
  if f1.nil? or f2.nil?
    return false
  else
    transaction do
      f1.destroy
      f2.destroy
      return true
    end
  end
end

用户模型:

      has_many :doweets
  has_many :friendships
  has_many :friends, 
           :through => :friendships,
           :conditions => "status = 'accepted'"

  has_many :requested_friends, 
           :through => :friendships, 
           :source => :friend,
           :conditions => "status = 'requested'", 
           :order => :created_at

  has_many :pending_friends, 
           :through => :friendships, 
           :source => :friend,
           :conditions => "status = 'pending'", 
           :order => :created_at

谢谢!

编辑:

我的错误: NoMethodError:#

的未定义方法`doweets'

1 个答案:

答案 0 :(得分:0)

ids = [current_user.id, *current_user.friends.map(&:id)]
@statuses = Status.where(:user_id => ids).limit(10).order("created_at DESC")

就是这样