ruby-on-rails – NoMethodError – []的未定义方法’find_by’:ActiveRecord :: Relation

我一直在关注Michael Heartl教程来创建一个跟随系统,但我有一个奇怪的错误:“未定义的方法`find_by’为[]:ActiveRecord :: Relation”.我正在使用设计进行身份验证.

我的观点/users/show.html.erb看起来像这样:

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

用户模型’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

关系模型’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告诉我问题在于用户模型:“relationships.find_by(followed_id:other_user.id)”因为mthod没有定义,但我不明白为什么?

解决方法

我相信find_by是在rails 4中引入的.如果你没有使用rails 4,请将where_by替换为where和first.
relationships.where(followed_id: other_user.id).first

您还可以使用动态find_by_attribute

relationships.find_by_followed_id(other_user.id)

在旁边:

我建议你改变你的追随者?返回truthy值而不是记录的方法(或没有找到记录时为n​​il).你可以使用exists吗?

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

这样做的一大优点是它不会创建任何对象,只返回一个布尔值.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...