2013-07-19 16 views
7

Śledziłem samouczek Michaela Heartla, aby stworzyć system śledzenia, ale mam dziwny błąd: "niezdefiniowana metoda` find_by 'for []: ActiveRecord: :Relacja". Używam devise do uwierzytelniania.NoMethodError - niezdefiniowana metoda 'find_by' dla []: ActiveRecord :: Relation

Mój pogląd /users/show.html.erb wygląda tak:

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

użytkownika modelu 'models/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 

modelu związku „models/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 mówi mi, że problem jest w modelu użytkownika: "relationships.find_by (followed_id: other_user.id)", ponieważ m thod nie jest zdefiniowany, ale nie rozumiem dlaczego?

Odpowiedz

22

wierzę find_by został wprowadzony w szynach 4. Jeśli nie używasz szyny 4, wymienić find_by przez połączenie where i first.

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

Można również użyć dynamicznej find_by_attribute

relationships.find_by_followed_id(other_user.id) 

marginesie:

Proponuję zmienić metodę following? zwrócić wartość truthy zamiast rekordu (lub zero gdy nie rekord jest uznany). Możesz to zrobić, używając exists?.

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

Jedną dużą zaletą tego jest to, że nie tworzy żadnego obiektu i po prostu zwraca wartość boolowską.

+0

działa, dzięki! I masz rację, jeśli chodzi o wartość boolowską, jest znacznie lepsza. – titibouboul

2

Można użyć

relationships.find_by_followed_id(other_user_id) 

lub

relationships.find_all_by_followed_id(other_user_id).first 
Powiązane problemy