![](/img/trans.png)
[英]Rails/Arel: Selecting all records as an ActiveRecord::Relation
[英]Mutual friends as an ActiveRecord Arel Relation
我的用戶有以下型號:
class User < ActiveRecord::Base
has_many :facebook_friendships
has_many :facebook_friends, :through => :facebook_friendships, :source => :friend
def mutual_facebook_friends_with(user)
User.find_by_sql ["SELECT users.* FROM facebook_friendships AS a
INNER JOIN facebook_friendships AS b
ON a.user_id = ? AND b.user_id = ? AND a.friend_id = b.friend_id
INNER JOIN users ON users.id = a.friend_id", self.id, user.id]
end
end
class FacebookFriendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => 'User'
end
如果id為53的用戶和id為97的用戶是彼此的朋友,那么您將在數據庫的facebook_friendships表中擁有行[53,97]和[97,53]。 這是我用來計算共同朋友的原始SQL查詢:
SELECT users.* FROM facebook_friendships AS a
INNER JOIN facebook_friendships AS b
ON a.user_id = :user_a AND b.user_id = :user_b AND a.friend_id = b.friend_id
INNER JOIN users ON users.id = a.friend_id
我會將mutual_friends_with返回一個關系而不是一個數組。 通過這種方式,我可以將結果與其他條件(例如where(大學:'NYU'))聯系起來,並獲得所有ActiveRecord的優點。 有沒有辦法做到這一點?
你試過#find_by_sql
嗎?
http://guides.rubyonrails.org/active_record_querying.html#finding-by-sql
如果您想使用自己的SQL在表中查找記錄,可以使用find_by_sql。 即使基礎查詢只返回單個記錄,find_by_sql方法也將返回一個對象數組。 例如,您可以運行此查詢:
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
find_by_sql為您提供了一種對數據庫進行自定義調用並檢索實例化對象的簡單方法。
這就是我用來結交共同朋友的方式。
has_many :company_friendships, autosave: true
has_many :company_friends, through: :company_friendships, autosave: true
has_many :inverse_company_friendships, class_name: "CompanyFriendship", foreign_key: "company_friend_id", autosave: true
has_many :inverse_company_friends, through: :inverse_company_friendships, source: :company, autosave: true
def mutual_company_friends
Company.where(id: (company_friends | inverse_company_friends).map(&:id))
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.