2013-07-19 31 views
7

Tôi đã theo hướng dẫn của Michael Heartl để tạo ra một hệ thống theo dõi nhưng tôi có một lỗi lạ: "phương thức undefined` find_by 'cho []: ActiveRecord: :Quan hệ". Tôi đang sử dụng tính năng xác thực.NoMethodError - phương thức undefined 'find_by' cho []: ActiveRecord :: Relation

xem /users/show.html.erb của tôi trông như thế:

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

tài mô hình 'mô hình/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 

mô hình mối quan hệ 'mô hình/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 

Đường ray cho tôi biết sự cố trong mô hình người dùng: "relationship.find_by (follow_id: other_user.id)" vì m thod không được định nghĩa, nhưng tôi không hiểu tại sao?

Trả lời

22

Tôi tin rằng find_by đã được giới thiệu trong đường ray 4. Nếu bạn không sử dụng đường ray 4, hãy thay thế find_by bằng cách kết hợp wherefirst.

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

Bạn cũng có thể sử dụng động find_by_attribute

relationships.find_by_followed_id(other_user.id) 

sang một bên:

tôi đề nghị bạn thay đổi phương thức following? của bạn để trả về một giá trị truthy chứ không phải là một kỷ lục (hoặc nil khi không có hồ sơ là tìm). Bạn có thể làm điều này bằng cách sử dụng exists?.

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

Một lợi thế lớn của việc này là nó không tạo ra bất kỳ đối tượng nào và chỉ trả về giá trị boolean.

+0

làm việc, cảm ơn! Và bạn đúng với giá trị boolean, nó tốt hơn nhiều. – titibouboul

2

Bạn có thể sử dụng

relationships.find_by_followed_id(other_user_id) 

hoặc

relationships.find_all_by_followed_id(other_user_id).first 
Các vấn đề liên quan