2012-08-06 63 views
0

我有一个基本的社交网络。 我想创建一个返回用户数组的朋友方法。某些user :ids属于:user_id属性,有些属于:friend_id属性。我不想退还current_user.id。我只想返回:name,:id:uid属性。我不知道该从哪里出发。找朋友并创建用户数组

我希望我简化一下,请告诉我,如果我的问题是缺乏信息。

谢谢!

class User < ActiveRecord::Base 
    has_many :friendships, :conditions => {:accepted => true} 
    has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id", :conditions => {:accepted => true} 

    attr_accessible :name, :oauth_expires_at, :oauth_token, :provider, :uid 

    def friends 
    friendships.preload(:friend) + inverse_friendships.preload(:user) 
    end 
end 

class Friendship < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :friend, :class_name => "User" 
    attr_accessible :accepted, :friend_id, :user_id, :friend 
end 
+0

问题是有些含糊,什么是你的模型中的列? – Ari 2012-08-06 15:56:05

+0

对不起,如果有点不清楚。我更新了它。你需要更多信息吗? – Dol 2012-08-06 16:00:59

回答

0

如何:

class User 
    ... 
    def friends 
    friendships.map { |f| [f.name, f.id, f.uid] } 
    end 

end 
+0

差不多....没有映射友谊我需要映射友谊的用户。对不起,也许我的问题还不够清楚。但你的答案帮助我找到答案,因为你的方法是正确的!答案是:friendships.preload(:friend).map {| f | [f.friend.name,f.friend.id,f.friend.uid]} + inverse_friendships.preload(:user).map {| f | [f.user.name,f.user.id,f.user.uid]}。全部在一行中。所以,如果你改变你的答案,我会标记为未来的编码人员很容易找到正确的。谢谢!! – Dol 2012-08-07 08:51:22

+0

有没有办法显示属性呢?该数组作为原始数据出现,在视图中调用时它不理解。 – Dol 2012-08-07 09:14:28

相关问题