如何使方法在seeds.rb中工作

时间:2012-11-26 04:47:30

标签: ruby-on-rails ruby-on-rails-3 rake-task

我正在为#undefined method $ rake db:seeds`做错误when lauch add_friend'。我试图通过rake任务添加好友,它在User模型中定义。但该方法无法使用。

这是db / seeds.rb文件

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

并且有用户文件。

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

1 个答案:

答案 0 :(得分:4)

使add_friend成为一个类方法

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

或将其称为User.new.add_friend(User.all[rand(User.count)])

HTH