ruby on rails - NoMethodError - undefined method 'find_by' for []:ActiveRecord::Relation -


i've been following michael heartl tutorial create follow system have strange error: "undefined method `find_by' []:activerecord::relation". i'm using devise authentication.

my view /users/show.html.erb looks 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 telling me issue in user model : "relationships.find_by(followed_id: other_user.id)" because mthod not defined, don't understand why ?

i believe find_by introduced in rails 4. if not using rails 4, replace find_by combination of where , first.

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

you can use dynamic find_by_attribute

relationships.find_by_followed_id(other_user.id) 

aside:

i suggest change following? method return truthy value rather record (or nil when no record found). can using exists?.

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

one big advantage of doesn't create object , returns boolean value.


Comments