繁体   English   中英

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

[英]How to make a method work in seeds.rb

我正在和错误的undefined method add_friend'for# when lauch $ rake db:seeds`。我试图通过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

使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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM