Frage

I would like to allow the users to 'create' and 'update' their submissions (bets) until a specific date and time at which point their bets are final (can no longer be created or updated). This process would repeat each week.

I'm fairly new to Rails and I'm not sure if there is a term for this or what to search for.

Can anyone point me in the right direction?

War es hilfreich?

Lösung

Probably the easiest way to achieve this is just to add a before_filter (Rails 3.x) or before_action (Rails 4.x) to your controller. You can do so like this:

Assume you have submissions_controller.rb with create/update actions like so - add a before filter that will only apply to the create and update actions. You can then implement a private method in the controller to redirect the user back to your root_path or elsewhere and give a flash message as to why.

class PagesController < ApplicationController
  before_filter :check_if_bets_are_final, :only => [:create, :update]

  def create
    ...
  end

  def update
    ...
  end

  private
    def check_if_bets_are_final
      if Time.now >= Time.new(2014, 02, 20)
        flash[:error] = "You can no longer modify or submit new bets!"
        redirect_to root_path
      end
    end

end

Aside from your controller action though, it will probably be safer to implement a model-level validation/check to reject it if the date is past, just to be safe (or if you have other ways to update that object in the future). You can do this through the model hook before_save, in which you can pretty much do a similar check that I have given above.

Also, the other caveat is that comparing Time.now could be in a different timezone depending on where your server is. Just be cognisant of this when you do your checks, and cast the time properly with this in mind.

Andere Tipps

Since you didn't provide a specific implementation, I'm not quite sure if you're having trouble specifically with Ruby or Rails. However, given your question, I would store a datetime variable in your database when the user creates the bet. Every time the user tries to 'update' the bet, check in the database whether or not it's been past that specific time away from the bet creation. Hope this helps.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top