簡體   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