简体   繁体   中英

Check if record exists in Model Rails

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM