2011-12-13 34 views
1

定义值我有一个模型:我正确的方法在模型

class Cars < ActiveRecord::Base 

    tag_nr = rand(2007) 

end 

Cars模型映射到cars数据库的列nameowner

正如你在上面看到的,还有一个tag_nr,它基本上是一个的随机数

我想有每个实例对象Cars类的持有像上面生成一个随机数但是我不想让这个随机数存储在数据库中。而在将来,我可以访问这个实例对象通过的tag_nr

nr = CAR_INSTANCE.tag_nr 

而且nr现在是相同tag_nr这个汽车实例对象首先生成。

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

回答

3

一个简单的方法是用after_initialize方法:(?3.0为好)

class Cars < ActiveRecord::Base 
    after_initialize :init 

    attr_accessor :tag_nr 

    def init 
    @tag_nr = rand(2007) 
    end 
end  

这是现在在3.1回调方法:

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

该方法是否支持Rails v2.3.2? –

+0

@ Leem.fin [是(apidock文档)](http://apidock.com/rails/v2.3.2/Rails/Initializer/after_initialize),虽然你的问题是用Rails 3标记的。 –

0

你可以把代码放到你的“ lib”目录下保存为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会为您提供一个实例,但如果您尝试使用其他相同类实例创建新实例,则代码出现问题。

相关问题