9

I've been following Michael Heartl tutorial to create a follow system but I have a strange error: "undefined method `find_by' for []:ActiveRecord::Relation". I'm using devise for authentication.

My view /users/show.html.erb looks like that:

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

User model '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

Relationship model '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 is telling me that the issue is in user model : "relationships.find_by(followed_id: other_user.id)" because mthod is not defined, but I don't understand why ?

4

2 回答 2

25

我相信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?方法以返回真实值而不是记录(或在未找到记录时返回 nil)。您可以使用exists?.

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

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

于 2013-07-19T16:08:51.783 回答
3

您可以使用

relationships.find_by_followed_id( other_user_id ) 

或者

relationships.find_all_by_followed_id( other_user_id ).first
于 2013-10-03T02:35:15.717 回答