0

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

我有一个预测模型,其中用户提交他们对一组足球比赛的预测得分,它们按fixture_date 分组。

如果用户已经提交了对这些游戏的预测,我想显示一条错误消息,说明他们无法提交,因为错误存在,或者如果日期的预测存在,则可能不显示表单。此时我可以创建同一游戏的多组预测。可能验证会更好。我将如何说明如果当前用户在该日期存在预测然后不提交?

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

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
4

1 回答 1

1

我不确定预测和游戏之间的关系。你有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
于 2013-05-10T10:14:05.547 回答