2013-07-19 26 views
7

Takip eden bir sistem oluşturmak için Michael Heartl öğreticisini takip ediyorum ama garip bir halim var: "undefined method find_by" []: ActiveRecord: : İlişkisi". Kimlik doğrulama için kullanıyorum.NoMethodError - undefined method 'find_by' için []: ActiveRecord :: Relation

Bence /users/show.html.erb benziyor:

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

Kullanıcı modeli 'modelleri/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 

İlişki modeli 'modelleri/relationship.rb ':

Raylar konu kullanıcı modelinde olduğunu bana anlatıyor
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 

: "relationships.find_by (followed_id: other_user.id)" çünkü m thod tanımlı değil ama nedenini anlamıyorum. Ben find_by inanıyoruz

cevap

22

Eğer raylar 4 kullanmıyorsanız, where ve first kombinasyonu ile find_by yerine raylar 4'te tanıtıldı. KENARA

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

da kullanabilirsiniz dinamik find_by_attribute

relationships.find_by_followed_id(other_user.id) 

:

Ben hiçbir kayıt olduğunda yerine bir rekor daha truthy değer döndürmek için following? yöntemini değiştirmek (veya sıfır önermek bulundu). Bunu exists? kullanarak yapabilirsiniz.

Bunun büyük bir avantajı, herhangi bir nesne oluşturmaması ve yalnızca bir boole değeri döndürmesidir.

+0

Çalışma kullanabilirsiniz, teşekkürler! Ve sen boole değeri için haklısın, daha iyi. – titibouboul

2

Sen

relationships.find_by_followed_id(other_user_id) 

veya

relationships.find_all_by_followed_id(other_user_id).first 
İlgili konular