1

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

这是 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
4

1 回答 1

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)])

高温高压

于 2012-11-26T04:52:04.057 回答