Rails:redirect_to之后从嵌入表单中丢失flash /错误

时间:2010-12-09 20:48:30

标签: ruby-on-rails partial-views has-many partials

这是一个愚蠢的例子,但我试图理解Rails中的幕后传递方式。并且可能有更好的“Rails”方法来解决这个问题......如果是这样,请告诉我。我有:

Warren has_many Rabbits
Rabbit belongs_to Warren

我列出了现有的兔子,然后提供了添加新兔子的表格。

窥伺/ show.html.haml

%h1 This Warren

%h2 Rabbits
= render @warren.rabbits, :target => @warren

%h2 Add a rabbit:
= render "rabbits/form", :parent => @warren, :foreign_key => :warren_id

= link_to 'Edit', edit_warren_path(@warren)
\|
= link_to 'Back', warrens_path

有效。我可以在看Warren的节目视图的同时添加和销毁兔子。问题是 flash 消息(:success:notice)和/或rabbit.errors未在视图中/上显示。现在,我在我的warren.rb模型中使用accepts_nested_attributes_for 。但这主要是工作。学习Rails所以想知道发生了什么,如何让我的消息顺利流动 ......

兔/ _form.html.haml

= form_for ([parent, parent.rabbits.build]) do |f| 
    = render "shared/error_messages", :target => parent

    .field
        = f.label :name
        = f.text_field :name
    .field
        = f.label :color
        = f.text_field :color
    .field
        = f.hidden_field foreign_key
    .actions
        = f.submit 'Save'

布局/ application.html.haml

    !!!
    %html
        %head
               ...
        %body
            .container
                - flash.each do |key, value|
                    %div{ :class => ['flash', key] }= value
                = yield

rabbits_controller.rb

class RabbitsController < ApplicationController

  def create
    @warren = Warren.find(params[:warren_id])
    @rabbit = @warren.rabbits.create(params[:rabbit])
    redirect_to @warren
  end

  def destroy
    @warren = Warren.find(params[:warren_id])
    @rabbit = @warren.rabbits.find(params[:id])
    @rabbit.destroy
    redirect_to @warren
  end

共享/ _error_messages.html.haml

-if target.errors.any?
  #error_explanation
    %h2= "#{pluralize(target.errors.count, "error")} prohibited this record from being saved:"
    %ul
      - target.errors.full_messages.each do |msg|
        %li= msg

1 个答案:

答案 0 :(得分:2)

似乎您没有在控制器中设置闪存消息。请尝试以下方法:

def create
  @warren = Warren.find(params[:warren_id])
  @rabbit = @warren.rabbits.create(params[:rabbit])
  redirect_to @warren, :flash => { :info => "Rabbit was just born." }
end

def destroy
  @warren = Warren.find(params[:warren_id])
  @rabbit = @warren.rabbits.find(params[:id])
  @rabbit.destroy
  redirect_to @warren, :flash => { :info => "Rabbit was brutally murdered!" }
end

或者,我相信您可以使用:success / notice

redirect_to @warren, :success => "Rabbit was brutally murdered!"

希望这有帮助!

<强>更新

对于您的错误消息,您需要target.error_messages之类的内容。您可以找到有关自定义输出here的更多详细信息。