我的模型中有一个像这样的验证
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
作为用户的想法只能为每个灯具做出一个预测,如果他们尝试为同一灯具提交另一个预测,那么他们会收到一条消息,指出无法提交。
我正在像这样使用form_tag
<%= form_tag controller: 'predictions', action: 'create', method: 'post' do %>
<%= error_messages_for :prediction %><!-- Just added this -->
<% @fixture_date.sort.each do |date, fixture| %>
<%= date_format(date) %>
<% fixture.each do |fixture|%>
<%= fixture.home_team %>
<%= text_field_tag "predictions[][home_score]" %>
<%= text_field_tag "predictions[][away_score]" %>
<%= fixture.away_team %>
<%= hidden_field_tag "predictions[][home_team]", fixture.home_team %>
<%= hidden_field_tag "predictions[][away_team]", fixture.away_team %>
<%= hidden_field_tag "predictions[][fixture_date]", fixture.fixture_date %>
<%= hidden_field_tag "predictions[][fixture_id]", fixture.id %>
<%= hidden_field_tag "predictions[][user_id]", current_user.id %>
<% end %>
控制者
def create
begin
params[:predictions].each do |prediction|
Prediction.new(prediction).save!
end
redirect_to root_path, :notice => 'Predictions Submitted Successfully'
end
end
目前我正在变得相当丑陋,不切实际
ActiveRecord::RecordInvalid in PredictionsController#create
Validation failed: Fixture only one prediction per game is allowed, for each user
如何获取错误信息以显示在页面上
我以为这样可以
<%= error_messages_for :prediction %>
如上所述,但没有
任何帮助表示赞赏
最佳答案
使用save
返回 bool(boolean) 值,然后添加模型并附加错误。save!
,引发异常。
关于ruby-on-rails - 事件记录错误消息form_tag Rails 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16483025/