活动记录错误消息form_tag Rails 3

时间:2013-05-10 13:07:30

标签: ruby-on-rails ruby-on-rails-3 validation error-handling rails-activerecord

我在我的模型中验证了如此

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 %>

如上所述,但它没有

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:1)

使用返回布尔值的save并添加你的模型会附加错误。

save!,抛出异常。