0

I was wondering if i would need to create a custom validation for the following scenario.

I have a Prediction model, in which a user submits their predicted scores for a set of football matches, they are grouped by fixture_date.

If a user has already submitted predictions for these games already i would like to show an error message stating they are unable to submit as the error exists, or maybe not show the form if the predictions for the dates exist.At the moment I can create multiple sets of predictions for the same games. Probably the validation would be better. How would i go about stating that if a prediction exists for that date for the current_user then do not submit?

So my setup looks like this so far

class Prediction < ActiveRecord::Base attr_accessible :home_team, :away_team, :home_score, :away_score, :fixture_date, :fixture_id, :user_id has_one :fixture end class Fixture < ActiveRecord::Base attr_accessible :home_team, :away_team, :fixture_date, :kickoff_time, :prediction_id end 

Predictions Controller

 def index @predictions = current_user.predictions if current_user.predictions end def new @prediction = Prediction.new end def create begin params[:predictions].each do |prediction| Prediction.new(prediction).save! end redirect_to root_path, :notice => 'Predictions Submitted Successfully' rescue render 'new' end end end 
1
  • you forgot belongs_to :prediction in your fixture model, maybe this causes the error. Commented May 10, 2013 at 10:05

1 Answer 1

1

Im not sure about the relation between predictions and games. Do you have a Game model? If so then something like this should work:

class Prediction < ActiveRecord::Base attr_accessible :home_team, :away_team, :home_score, :away_score, :fixture_date, :fixture_id, :user_id has_one :fixture validates :fixture_id, :uniqueness => { :scope => :user_id, :message => "only one prediction per game is allowed, for each user" } end 
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your answer, game model? its a fixture and prediction model
This would work so a user could only have one prediction for each fixture... But im not sure if this is want you want to archieve?
yes this is fine, later on though and not relevant to the question a user will be able to make multiple predicitons based on how many leagues they belong to, but as i said not relevant to this question..thanks :) Im just testing the code now
seems as if rescue may be causing me an issue? cant get the message to display when record already exists.i get the default error page Validation failed: Fixture has already been taken

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.