我的模型中有这样的验证
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 %>
如上,但它没有
任何帮助表示赞赏