ruby-on-railsruby-on-rails-3rake-task

How to make a method work in seeds.rb


I'm having and error undefined methodadd_friend' for #when lauch$ rake db:seeds` .I'am trying to add friend via the rake task , it's define in the User model. But the method is unusable .

Here is the db/seeds.rb file

require 'faker'
require 'populator'

User.destroy_all

10.times do
  user = User.new
  user.username = Faker::Internet.user_name
  user.email = Faker::Internet.email
  user.password = "test"
  user.password_confirmation = "test"
  user.save
end


User.all.each do |user|  
  Flit.populate(5..10) do |flit|
    flit.user_id = user.id
    flit.message = Faker::Lorem.sentence
  end

  3.times do
    User.add_friend(User.all[rand(User.count)])
  end
end

and there is the user file.

class User < ActiveRecord::Base
  # new columns need to be added here to be writable through mass assignment
  attr_accessible :username, :email, :password, :password_confirmation

  attr_accessor :password
  before_save :prepare_password

  validates_presence_of :username
  validates_uniqueness_of :username, :email, :allow_blank => true
  validates_format_of :username, :with => /^[-\w\._@]+$/i, :allow_blank => true, :message => "should only contain letters, numbers, or .-_@"
  validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
  validates_presence_of :password, :on => :create
  validates_confirmation_of :password
  validates_length_of :password, :minimum => 4, :allow_blank => true

  has_many :flits, :dependent => :destroy

  has_many :friendships
  has_many :friends, :through => :friendships



  def add_friend(friend)
    friendship = friendships.build(:friend_id => friend.id)
      if !friendship.save
        logger.debug "User '#{friend.email}' already exists in the user's friendship list."
      end
  end

  # login can be either username or email address
  def self.authenticate(login, pass)
    user = find_by_username(login) || find_by_email(login)
    return user if user && user.password_hash == user.encrypt_password(pass)
  end

  def encrypt_password(pass)
    BCrypt::Engine.hash_secret(pass, password_salt)
  end

  private

  def prepare_password
    unless password.blank?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash = encrypt_password(password)
    end
  end
end

Solution

  • Make add_friend a class method:

    def self.add_friend(friend)
        friendship = friendships.build(:friend_id => friend.id)
          if !friendship.save
            logger.debug "User '#{friend.email}' already exists in the user's friendship list."
          end
    end
    

    or call it as User.new.add_friend(User.all[rand(User.count)]).