我想在用户建立投票时添加“可用时间”。如何实施?
比如我设置了一个投票,2012.1.1可以投票。另外,投票的“可用时间”从一天到一年不等。
我想在用户建立投票时添加“可用时间”。如何实施?
比如我设置了一个投票,2012.1.1可以投票。另外,投票的“可用时间”从一天到一年不等。
添加一个日期列,如“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
你需要两个模型:
投票.rb
class Voting < ActiveRecord::Base
has_many :votes
def expired?
self.expires_at < Date.today
end
end
投票.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