NoMethodError - []的未定义方法'find_by':ActiveRecord :: Relation

时间:2013-07-19 15:54:15

标签: ruby-on-rails devise rails-activerecord nomethoderror

我一直在关注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没有定义,但我不明白为什么?

2 个答案:

答案 0 :(得分:25)

我认为导轨4中引入了find_by。如果您不使用导轨4,请将find_bywhere的组合替换为first

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

您还可以使用动态find_by_attribute

relationships.find_by_followed_id(other_user.id)

ASIDE:

我建议您更改following?方法以返回真值而不是记录(或未找到记录时为零)。您可以使用exists?

执行此操作
relationships.where(followed_id: other_user.id).exists?

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

答案 1 :(得分:3)

您可以使用

relationships.find_by_followed_id( other_user_id ) 

relationships.find_all_by_followed_id( other_user_id ).first