0

我之前没有遇到过验证问题,但这次我遇到了nested_form 验证问题。我正在使用 Twitter Bootstrap,并且可以通过以下方式显示 flash 错误:

 def create
 @recipe = current_user.recipes.new(params[:recipe])
 if @recipe.save
  redirect_to my_recipes_path, :notice => "Thanks #{current_user.name} Recipe sucessfully created."
  else
  render :action => 'new'
 end
end

对于我的 Flash 消息,我在我的应用程序/布局中使用它

 <% flash.each do |name, msg| %>
 <div class="alert alert-<%= name == :notice ? "success" : "error" %>">
  <a class="close" data-dismiss="alert">×</a>
  <%= content_tag :div, msg, :id => "flash_#{name}" if msg.is_a?(String) %>
 </div>
 <% end %>

所以我想我会尝试让其中一个验证器工作,所以我的模型

class Recipe < ActiveRecord::Base

belongs_to :user
delegate :name, :to => :user, :prefix => :user, :allow_nil => true
belongs_to :country
has_many :ingredients 
has_many :preperations
has_many :favourites

validates_presence_of :dish_name

和我的表格

    <%= nested_form_for @recipe  do |f| %>

    <div class="field_with_errors"> 
    <%= f.label :dish_name, "Dish Name" %>
    <%= f.text_field :dish_name, :placeholder => "Enter Dish Name" %>
    </div>


    <%= f.label :country_id, "Country Of Origin" %>
    <%= f.collection_select(:country_id, Country.all, :id, :name, :prompt => 'Please select country') %>

    <%= f.label :category, "Category" %>
    <%= f.select :category, [['Starter'], ['Main Course'], ['Desserts'],  ['Vegeterian']], {:include_blank => 'Please Select'} %>


   <%= f.label :difficulty, "Difficulty Level" %>
   <%= f.select :difficulty, [['Beginner'],['Intermediate'],['Expert']], {:include_blank => 'Please Select'} %>

   <%= f.label :preperation_time, "Preperation Time (Mins)" %>
   <%= f.select :preperation_time, [['15-30 Mins'],['30-60 Mins'],['60-120 Mins']], {:include_blank => 'Please Select'} %>

   <%= f.fields_for :ingredients do |ing| %>
   Ingredient<br>
   <%= ing.text_field :ingredient_name , :placeholder => "Enter Ingredient Here" %><br>
   <% end %>
   <%= f.link_to_add "Add an Ingredient", :ingredients %><br>

   <%= f.fields_for :preperations do |prep| %>
   Preperation Step<br>
   <%= prep.text_field :prep_steps , :placeholder => "Enter step Here" %><br>
   <% end %>

   <%= f.link_to_add "Add a step", :preperations %><br>

   <%= f.label :description, "Description of Recipe" %>
   <%= f.text_area :description, :size=> "60x10" %></br>

   <%= f.file_field :avatar %><br>

   <%= f.submit "Submit Recipe" %>
   <% end %>

我对 Rails 还很陌生,所以我可能错过了一些基本的东西,还是因为它是一个嵌套形式并且行为不同?

编辑

输出<%= flash debug %>

  --- !ruby/object:ActionDispatch::Flash::FlashHash
 used: !ruby/object:Set
 hash: {}
 closed: false
 flashes: {}
 now:
4

1 回答 1

2

看来您实际上并没有为您的闪存哈希提供任何可使用的消息。一个快速的解决方案可能是这样的:

def create
 @recipe = current_user.recipes.new(params[:recipe])
 if @recipe.save
   redirect_to my_recipes_path, :notice => "Thanks #{current_user.name} Recipe sucessfully created."
 else
   flash[:error] =  @recipe.errors.full_messages.to_sentence
   render :action => 'new'
 end
end
于 2012-12-19T21:39:55.070 回答