1

ユーザーが投票を確立するときに「利用可能な時間」を追加したい。実装方法は?

たとえば、私は投票を設定し、2012.1.1 までに投票できます。さらに、投票の「有効時間」の範囲は 1 日から 1 年です。

4

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

次の 2 つのモデルが必要です。

投票.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
于 2011-10-12T01:59:43.050 に答える