我正确地定义模型中的值

时间:2011-12-13 13:58:15

标签: ruby-on-rails

我有一个模特:

class Cars < ActiveRecord::Base

  tag_nr = rand(2007)

end

Cars模型已映射到数据库中的cars表,列nameowner

如上所述,还有tag_nr基本上是随机数

我希望Cars 的每个实例对象持有如上所述生成的随机数我不希望将此随机数存储在数据库中。将来,我可以通过:

访问此实例对象的tag_nr
nr = CAR_INSTANCE.tag_nr

nr现在与首次为此Cars实例对象生成的tag_nr 相同

那么,我应该在哪里以及如何在我的Car模型中定义这个随机数?

2 个答案:

答案 0 :(得分:3)

一种简单的方法是使用after_initialize方法:

class Cars < ActiveRecord::Base
  after_initialize :init

  attr_accessor :tag_nr

  def init
    @tag_nr = rand(2007)
  end
end    

现在这是3.1中的回调方法(3.0以及?):

after_initialize do |car|
  puts "You have initialized an object!"
end

答案 1 :(得分:0)

您可以将该代码放入&#39; lib&#39;目录另存为find_random.rb

module FindRandom
  # pull out a unique set of random active record objects without killing
  # the db by using "order by rand()"
  # Note: not true-random, but good enough for rough-and-ready use
  #
  # The first param specifies how many you want.
  # You can pass in find-options in the second param
  # examples:
  #  Product.random     => one random product
  #  Product.random(3)  => three random products in random order
  #
  # Note - this method works fine with scopes too! eg:
  #  Product.in_stock.random    => one random product that fits the "in_stock" scope
  #  Product.in_stock.random(3) => three random products that fit the "in_stock" scope
  #  Product.best_seller.in_stock.random => one random product that fits both scopes
  #
  def find_random(num = 1, opts = {})
  # skip out if we don't have any
    return nil if (max = self.count(opts)) == 0

    # don't request more than we have
    num = [max,num].min

    # build up a set of random offsets to go find
    find_ids = [] # this is here for scoping

    # get rid of the trivial cases
    if 1 == num # we only want one - pick one at random
      find_ids = [rand(max)]
    else
      # just randomise the set of possible ids
      find_ids = (0..max-1).to_a.sort_by { rand }
      # then grab out the number that we need
      find_ids = find_ids.slice(0..num-1) if num != max
    end

    # we've got a random set of ids - now go pull out the records
    find_ids.map {|the_id| first(opts.merge(:offset => the_id)) }
  end
end

并像那样扩展您的模型

class Car < ActiveRecord::Base
  extend FindRandom

  def self.tag_nr
    self.random
  end
end 

调用Car.tag_nr将为您提供一个实例,但如果您尝试使用其他相同的类实例创建新实例,则代码出现问题。