2013-07-19 60 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 
相关问题