2015-11-01 73 views
1

我下面的邁克爾·哈特爾教程,並要設置的方法來限制用戶量的人可以按照用戶以下的配額限制

我應該設置的限制模型/ relationship.rb

應用程序/模型/ relationship.rb

validate :following_quota, :on => :create 

private 

def following_quota 
if user.active_relationships.size >= 3 
    error.add(:base, 'exceeded follow limit') 
end 
end 

或者我應該設置這樣的模型/ user.rb

+0

則需要使用自定義驗證器?什麼是主動關係?範圍?關係? – lcguida

+0

控制器或多或少地找出要渲染的視圖和持久性。這樣的代碼應該是模型中的自定義驗證。 – MarsAtomic

+0

@MarsAtomic是的,我已經在模型中設置了驗證 –

回答

0

如果你要參考相關的數據,你需要使用inverse_of;

#app/models/user.rb 
class User < ActiveRecord::Base 
    has_many :active_relationships, inverse_of: :user 
end 

#app/models/relationship.rb 
class Relationship < ActiveRecord::Base 
    belongs_to :user, inverse_of: :active_relationships 
end 

你把驗證的地方取決於你打電話給哪個模型。

我想像你正在創建一個新的relationship,這將意味着你把它放在關係模型,使用從user關聯對象數據:

#app/models/relationship.rb 
class Relationship < ActiveRecord::Base 
    belongs_to :user, inverse_of: :active_relationships 
    validate :max_followers, only: :create 

    private 

    def max_followers 
     error.add(:base, 'exceeded follow limit') if user.active_relationships.size >= 3 
    end 
end 
+0

我不認爲我需要創建關係的逆,如果我在關係控制器中有一個銷燬方法 - 現在我正在驗證max_followers驗證,並在日誌中得到這個錯誤:NoMethodError(undefined method'active_relationships 'for nil:NilClass): app/models/relationship.rb:16:in'max_followers' app/models/user.rb:46:in'follow' app/controllers/relationships_controller.rb:5:in'創建' –