0

Rails でエラーを表示するのに問題があります。これが私のコントローラーです

def new
    if current_user
        @edible = Edible.new 
    else 
        flash[:notice] = "You need to be signed in for this action"
        redirect_to root_path
    end
end

def create
    @edible = Edible.new(params[:edible])
    if @edible.valid? && current_user.edibles.push(@edible)
        if(params[:edible][:pickup] == "1")
            respond_to do |format|
                format.html { redirect_to new_user_edible_pick_up_adress(current_user.id, @edible.id) }
            end
        else
            respond_to do |format|
                format.html { redirect_to(user_edible_path(current_user.id, @edible.id), 
                               :success => "Product saved")
                             }
            end
        end

    else
        respond_to do |format|
            format.html { redirect_to(new_user_edible_path(current_user.id,
                :alert => "Error happend" ))
            }
        end

    end

end

形:

<%= nested_form_for @edible, :url => user_edibles_path,
    :html => { :multipart => true, :class => "signin" } do |f| %>
    <%= render 'shared/alerts', :object => @edible   %>
#standart code further...

そして部分的:

 <% if flash[:notice] %>
      <p class="notice"><%= flash[:notice] %></p>
    <% end %>
<% if flash[:error] %>
    <p class="error">
        <% if object %>
            <%= flash[:error] %>
            <ul>
            <% object.errors.full_messages.each do |msg| %>
                <li> <%= msg %> </li>
            <% end %>
            </ul>
        <% end %>
    </p>
<% end %>
<% if flash[:alert] %>
    <p class="alert"><%= flash[:alert] %></p>
<% end %>

新しいページにリダイレクトするときに @edible 変数が渡されていないと想定しているため、Rails は毎回新しいインスタンスで object.errors を実行します。明らかなことを見逃していますか?

4

2 に答える 2

1

新しいページにリダイレクトするときに @edible 変数が渡されていないと仮定します

正しい。HTTP はステートレス プロトコルであるため、これは当然のことです。

フォームにエラーを表示する秘訣は、エラーのあるオブジェクトがあるときにフォームをレンダリングすることです。つまり、モデルが作成アクションで検証に失敗した場合、リダイレクトする代わりにレンダリングする必要があります。

def create
    @edible = Edible.new(params[:edible])
    if @edible.valid? && current_user.edibles.push(@edible)
        # No changes here
    else
        respond_to do |format|
            format.html { render :new }  # Instead of redirecting just render the form
        end

    end

end
于 2013-05-09T13:01:13.760 に答える
0

flash[:notice] が書き込まれた後にリダイレクトがある場合、フラッシュはクリアされ、食用/新しいパスではなくルートパスに適用されるフラッシュ通知が表示されると思います。

テストとして、試してみてください:

def new
    if current_user
        @edible = Edible.new 
    else 
        flash[:notice] = "You need to be signed in for this action"
    end
end

これにより、ユーザーは「新しい」アクションのままになり、次を追加するだけです。

<%= flash[:notice] %>

「新規」アクションに移動して、サインインしていないときにエラーが表示されるかどうかを確認します。

于 2013-05-09T12:00:22.273 に答える