【问题标题】:Check if record exists in Model Rails检查 Model Rails 中是否存在记录
【发布时间】:2013-05-10 10:00:52
【问题描述】:

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

我有一个预测模型,其中用户提交他们对一组足球比赛的预测得分,它们按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

【问题讨论】:

  • 您忘记了您的夹具模型中的 belongs_to :prediction,这可能会导致错误。

标签: ruby-on-rails ruby-on-rails-3 validation model


【解决方案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

【讨论】:

  • 感谢您的回答,游戏模型?它是一个夹具和预测模型
  • 这会起作用,所以用户只能对每个灯具有一个预测......但我不确定这是否是你想要归档的?
  • 是的,这很好,但稍后与用户将能够根据他们所属的联赛数量做出多个预测的问题无关,但正如我所说的与这个问题无关。 .thanks :) 我现在只是测试代码
  • 似乎救援可能会给我带来问题?当记录已经存在时无法显示消息。我得到默认错误页面验证失败:夹具已被采用
猜你喜欢
  • 1970-01-01
  • 2013-08-07
  • 1970-01-01
  • 2023-03-22
  • 2013-05-16
  • 1970-01-01
  • 2011-02-20
相关资源
最近更新 更多