i want to add the "available time" when the user establish a vote . how to implement?
For example i set up a vote ,and it is available to vote by 2012.1.1.In addition ,the vote's "available time" range from one day to one year.
add a date column like "expires_at" and then you run a custom validation like:
Solution A*
if you have one single table called votings
:
id | name | votes | expires_at
expires_at
is a Date column
Now your model looks like (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
Now in your controller:
@voting = Voting.find(someid)
@voting.votes += 1
if @voting.save
# everyhing ok
else
# maybe the voting is closed, check validation messages
end
Solution B
If you have a 2-Table approach like:
Table Votings:
id | name | expires_at
Table Votes:
id | user_id | voting_id
You need two models:
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
Your Controller:
@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
Creating a new Voting:
@voting = Voting.new
@voting.name = 'President Election 2011'
@voting.expires_at = 1.year.from_now
@voting.save