2013-07-19 18 views
7

Ho seguito il tutorial di Michael Heartl per creare un sistema di follow ma ho uno strano errore: "metodo non definito` find_by 'per []: ActiveRecord: :Relazione". Sto usando Devise per l'autenticazione.NoMethodError - metodo non definito 'find_by' per []: ActiveRecord :: Relazione

mio punto di vista /users/show.html.erb sembra che:

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

utente modello di 'modelli/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 

modello di relazione 'modelli/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 mi sta dicendo che la questione è in modello di utente: "relationships.find_by (followed_id: other_user.id)" perché m Thod non è definito, ma non capisco perché?

risposta

22

Credo find_by è stato introdotto nel rotaie 4. Se non si utilizza rotaie 4, sostituire find_by da una combinazione di where e first.

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

È inoltre possibile utilizzare la dinamica find_by_attribute

relationships.find_by_followed_id(other_user.id) 

da parte:

ti suggerisco di cambiare il metodo di following? per restituire un valore truthy piuttosto che un record (o nullo quando nessun record è trovato). È possibile farlo utilizzando exists?.

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

Un grande vantaggio è che non crea alcun oggetto e restituisce semplicemente un valore booleano.

+0

di lavoro, grazie! E hai ragione per il valore booleano, è molto meglio. – titibouboul

2

È possibile utilizzare

relationships.find_by_followed_id(other_user_id) 

o

relationships.find_all_by_followed_id(other_user_id).first 
Problemi correlati