繁体   English   中英

检查Model Rails中是否存在记录

[英]Check if record exists in Model Rails

我想知道是否需要为以下情况创建自定义验证。

我有一个Prediction模型,在该模型中,用户提交了一组足球比赛的预测得分,这些得分按Fixture_date分组。

如果用户已经提交了这些游戏的预测,我想显示一条错误消息,指出由于存在错误而无法提交,或者如果日期的预测存在,则可能不显示表格。目前,我可以创建同一游戏的多组预测。 验证可能会更好。 我要如何声明,如果current_user对该日期存在预测,然后不提交?

所以到目前为止我的设置看起来像这样

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

预测控制器

 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

我不确定预测与博弈之间的关系。 你有Game模型吗? 如果是这样,那么类似的事情应该起作用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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