如何在投票上加上截止日期?

时间:2011-10-12 01:39:54

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 vote

我想在用户建立投票时添加“可用时间”。如何实施?

例如我设置投票,并且可以在2012.1.1之前投票。此外,投票的“可用时间”范围从一天到一年。

1 个答案:

答案 0 :(得分: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-Table方法,如:

表格投票:

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