2015-04-17 12 views
0

我在Rails 4中構建了一個社交網站。用戶可以請求關注另一個用戶。Rails 4關係狀態方法,這是最優的嗎?

在我的用戶模型中,我有以下方法。它的工作原理,但我想知道是否是確定關係狀態的最好方法。這個比例可以嗎?

謝謝。

def relationship_status(user_2) 
    relationship = Relationship.where(follower_id: self.id, followed_id: user_2.id) 
    unless relationship.any? 
    relationship = Relationship.where(followed_id: self.id, follower_id: user_2.id) 
    unless relationship.any? 
     return "not_friends" 
    else 
     if relationship.first.status == "pending" 
     return "pending_recieved" 
     elsif relationship.first.status == "ignored" 
     return "you_ignored" 
     elsif relationship.first.status == "active" 
     return "your_followed" 
     end 
    end 
    else 
    if relationship.first.status == "pending" 
     return "pending_sent" 
    elsif relationship.first.status == "ignored" 
     return "your_ignored" 
    elsif relationship.first.status == "active" 
     return "you_are_following" 
    end 
    end 
end 
+0

我想你在你的代碼中有一個錯誤。你定義的兩個關係都是一樣的! – fny

+0

where子句被顛倒過來。 follower_id和followed_id。 –

回答

0

我不認爲這將會很好地擴展,因爲您必須檢查每個操作的每個關係。更好的方法是將它們扇出並擴大查詢範圍

class User < ActiveRecord::Base 
    has_many :user_relationships, dependent:destroy, inverse_of :user 
    has_many :users, through: user_relationships 
    has_many :affected_user_relationships, class_name: UserRelatonship, dependent:destroy, foreign_key :affected_id 
    has_many :affected_users, through: user_relationships, source: :affected_user 

    has_many :ignored_relationships, dependent:destroy, inverse_of :user 
    has_many :ignored_users, through: ignored_relationships 

    # etc... 
end 

class UserRelationship 
    belongs_to :user 
    belongs_to :affected_user, class_name: User 

    validates_presence_of :user, :affected_user 
end 

class IgnoredRelationship < UserRelationship 
end 

class FollowedRelationship < UserRelationship 
end 

然後你可以做更快的查詢。

def ignored?(u) 
    self.ignored_users.include?(u) 
end 
0

這裏沒有什麼明顯不好的東西可以阻止你擴展性能。更大的縮放比例問題是您的代碼的清晰度,以及當您需要在4個月後進行更改時,您會多麼憎恨自己,但不記得您在此嘗試做什麼。

首先,你應該提取確定關係的性質爲你們的關係類方法的邏輯:

class Relationship 
    def following_status 
    case status 
    when 'pending' 
    'pending_sent' 
    when 'ignored' 
    'your_ignored' 
    when 'active' 
    'you_are_following' 
    end 
    end 

    def followed_status 
    case status 
    when 'pending_received' 
    'pending_sent' 
    when 'you_ignored' 
    'your_ignored' 
    when 'active' 
    'you_followed' 
    end 
    end 
end 

然後,我們可以用更有意義的變量名清理的關係狀態的方法

def relationship_status(other_user) 
    if following = Relationship.where(follower_id: self.id, followed_id: other_user.id).first 
    return following.following_status 
    end 
    if followed = Relationship.where(followed_id: self.id, follower_id: other_user.id).first 
    return followed.followed_status 
    end 
    'not_friends' 
end 

除外:Don't use unless and else together.該表格讀起來相當糟糕,並且變得非常令人目不暇接,尤其是在嵌套語句中。

相關問題