2011-10-12 46 views
1

我想在用戶建立投票時添加「可用時間」。如何實施?如何在投票上添加截止日期?

例如我設置了一個投票,它可以在2012.1.1投票。此外,投票的「可用時間」範圍從一天到一年。

回答

3

添加日期列,如 「expires_at」,然後你運行像一個自定義的驗證:

方案A *

,如果你有一個單獨的表名爲votings

id | name | votes | expires_at 

expires_at是日期列

現在你的模型看起來像(voting.rb ):

class Voting < ActiveRecord::Base 
    validate :check_expiry_date, :on => :update 

    def check_expiry_date 
    self.errors.add('base', 'Voting is closed') if self.expired? 
    end 

    def expired? 
    self.expires_at < Date.today 
    end 
end 

現在在你的控制器:

@voting = Voting.find(someid) 
@voting.votes += 1 

if @voting.save 
    # everyhing ok 
else 
    # maybe the voting is closed, check validation messages 
end 

溶液B

如果你有一個像2〜表的方法:

表分組表決:

id | name | expires_at 

表投票:

id | user_id | voting_id 

您需要兩個模型:

voting.rb

class Voting < ActiveRecord::Base 
    has_many :votes 

    def expired? 
    self.expires_at < Date.today 
    end 
end 

votes.rb

class Vote < ActiveRecord::Base 
    belongs_to :voting 
    belongs_to :user 

    # only one vote per user per voting 
    validates_uniqueness_of :user_id, :scope => :voting_id 

    # check expiry date 
    validate :check_expiry_date, :on => :create 

    def check_expiry_date 
    self.errors.add('base', 'Voting is closed') if self.voting.expired? 
    end 
end 

控制器:

@vote = Vote.new 
@vote.user_id = some_user_id 
@vote.voting_id = some_voting_id 

if @vote.save 
    # everything ok 
else 
    # maybe the voting is closed 
end 

創建一個新的投票:

@voting    = Voting.new 
@voting.name  = 'President Election 2011' 
@voting.expires_at = 1.year.from_now 
@voting.save 
+0

優秀!做得好! – Jack