2013-07-19 66 views
7

我一直在關注Michael Heartl教程來創建一個跟隨系統,但我有一個奇怪的錯誤:「未定義的方法find_by for []:ActiveRecord: :關係」。我正在使用設計進行身份驗證。NoMethodError - 未定義方法'find_by'for []:ActiveRecord :: Relation

我的觀點/users/show.html.erb看起來像這樣:

. 
. 
. 
<% if current_user.following?(@user) %> 
    <%= render 'unfollow' %> 
<% else %> 
    <%= render 'follow' %> 
<% end %> 

用戶模型 '模型/ user.rb':

class User < ActiveRecord::Base 
devise :database_authenticatable, :registerable, :recoverable, :rememberable,  :trackable, :validatable 

has_many :authentications 
has_many :relationships, foreign_key: "follower_id", dependent: :destroy 
has_many :followed_users, through: :relationships, source: :followed 
has_many :reverse_relationships, foreign_key: "followed_id", class_name: "Relationship", dependent: :destroy 
has_many :followers, through: :reverse_relationships, source: :follower 

    def following?(other_user) 
     relationships.find_by(followed_id: other_user.id) 
    end 

    def follow!(other_user) 
     relationships.create!(followed_id: other_user.id) 
    end 

    def unfollow!(other_user) 
     relationships.find_by(followed_id: other_user.id).destroy 
    end 

end 

關係模型「模型/ relationship.rb 「:

class Relationship < ActiveRecord::Base 

    attr_accessible :followed_id, :follower_id 

    belongs_to :follower, class_name: "User" 
    belongs_to :followed, class_name: "User" 

    validates :follower_id, presence: true 
    validates :followed_id, presence: true 

end 

Rails的告訴我,這個問題是在用戶模式: 「relationships.find_by(followed_id:other_user.id)」,因爲米thod沒有定義,但我不明白爲什麼?

回答

22

我認爲find_by是在rails 4中引入的。如果您未使用rails 4,請將find_by替換爲wherefirst的組合。

relationships.where(followed_id: other_user.id).first 

您也可以使用動態find_by_attribute

relationships.find_by_followed_id(other_user.id) 

旁白:

我建議你改變你的following?方法返回一個truthy值,而不是一個記錄(或無時無記錄找到)。您可以使用exists?來完成此操作。

relationships.where(followed_id: other_user.id).exists? 

這樣做的一大優點是它不會創建任何對象,只是返回一個布爾值。

+0

工作,謝謝!你對布爾值是正確的,它好多了。 – titibouboul

2

您可以使用

relationships.find_by_followed_id(other_user_id) 

relationships.find_all_by_followed_id(other_user_id).first 
相關問題