Ruby on rails 命名错误-未定义的方法';通过'查找#u;对于[]:ActiveRecord::Relation

Ruby on rails 命名错误-未定义的方法';通过'查找#u;对于[]:ActiveRecord::Relation,ruby-on-rails,devise,rails-activerecord,nomethoderror,Ruby On Rails,Devise,Rails Activerecord,Nomethoderror,我一直在遵循Michael Heartl教程来创建一个跟踪系统,但我有一个奇怪的错误:“未定义[]:ActiveRecord::Relation的方法'find_by'。我正在使用Desive进行身份验证 我的视图/users/show.html.erb如下所示: . . . <% if current_user.following?(@user) %> <%= render 'unfollow' %> <% else %> <%= re

我一直在遵循Michael Heartl教程来创建一个跟踪系统,但我有一个奇怪的错误:“未定义[]:ActiveRecord::Relation的方法'find_by'。我正在使用Desive进行身份验证

我的视图/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
class用户
关系模型“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(紧跟着\u id:other_user.id)”,因为mthod没有定义,但我不明白为什么?

我相信Rails 4中引入了
find_by
。如果不使用rails 4,请将
find_替换为
where
first
的组合

relationships.where(followed_id: other_user.id).first
您还可以使用动态
find_by_属性

relationships.find_by_followed_id(other_user.id)
旁白:

我建议您更改
following?
方法,以返回真实值而不是记录(如果找不到记录,则返回nil)。您可以使用
存在?
来执行此操作

relationships.where(followed_id: other_user.id).exists?
它的一大优点是不创建任何对象,只返回一个布尔值。

您可以使用

relationships.find_by_followed_id( other_user_id ) 


工作,谢谢!对于布尔值,你是对的,它要好得多。
relationships.find_all_by_followed_id( other_user_id ).first