2011-12-13 33 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會爲您提供一個實例,但如果您嘗試使用其他相同類實例創建新實例,則代碼出現問題。

相關問題