NoMethodError - неопределенный метод find_by для []:ActiveRecord::Relation

Я следил за учебником Майкла Хартла, чтобы создать систему отслеживания, но у меня есть странная ошибка: "неопределенный метод `find_by' для []:ActiveRecord::Relation". Я использую devise для аутентификации.

Мой вид /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 не определен, но я не понимаю, почему?


person titibouboul    schedule 19.07.2013    source источник


Ответы (2)


Я считаю, что find_by был представлен в rails 4. Если вы не используете rails 4, замените find_by комбинацией where и first.

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

Вы также можете использовать динамический find_by_attribute

relationships.find_by_followed_id(other_user.id)

В СТОРОНЕ:

Я предлагаю вам изменить метод following?, чтобы он возвращал истинное значение, а не запись (или nil, если запись не найдена). Вы можете сделать это, используя exists?.

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

Одним из больших преимуществ этого является то, что он не создает никакого объекта и просто возвращает логическое значение.

person jvnill    schedule 19.07.2013
comment
Работаем, спасибо! И вы правы для логического значения, это намного лучше. - person titibouboul; 19.07.2013

Ты можешь использовать

relationships.find_by_followed_id( other_user_id ) 

or

relationships.find_all_by_followed_id( other_user_id ).first
person x2l2    schedule 03.10.2013