0

我有一个基本的 rails 4 脚手架应用程序,我的 routes.rb 看起来像这样:

scope ':username' do
   resources :recipes
end

然后我的控制器中的创建和更新操作如下所示:

def update
  respond_to do |format|
    if @recipe.update(recipe_params)
      format.html { redirect_to @recipe, notice: 'Recipe was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: 'edit' }
      format.json { render json: @recipe.errors, status: :unprocessable_entity }
    end
  end
end

然后创建:

def create
  @recipe = Recipe.new(recipe_params)
  @recipe.user = current_user.id
  respond_to do |format|
    if @recipe.save
      format.html { redirect_to @recipe, notice: 'Recipe was successfully created.' }
      format.json { render action: 'show', status: :created, location: @recipe }
    else
      format.html { render action: 'new' }
      format.json { render json: @recipe.errors, status: :unprocessable_entity }
    end
  end
end

我收到此错误:

ActionController::UrlGenerationError in Recipes#edit

显示第 1 行引发的 app/views/recipes/_form.html.erb:

No route matches {:action=>"show", :controller=>"recipes", :username=>#<Recipe id: 9, name: "jdsafkd", yield: "", description: "", duration: "", author: "", url: "", user: 6, image: "", created_at: "2013-07-09 18:07:50", updated_at: "2013-07-09 18:07:50">, :id=>nil, :format=>nil} missing required keys: [:id]

这是部分表格:

<%= form_for(@recipe) do |f| %>
    <% if @recipe.errors.any? %>
        <div id="error_explanation">
           <h2><%= pluralize(@recipe.errors.count, "error") %> prohibited this recipe from being saved:</h2>

        <ul>
         <% @recipe.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
         <% end %>
        </ul>
        </div>
    <% end %>
    <div class="field">
       <%= f.label :image %><br>
       <%= f.text_field :image %>
    </div>
    <div class="actions">
       <%= f.submit %>
    </div>
<% end %>

所以看起来我的重定向正在创建一个 UrlGeneration 错误,但我不知道为什么。

感谢大家的帮助!

4

1 回答 1

4

把它放在你的创建和更新方法中:

redirect_to recipe_path(username: current_user.username, id: @recipe.id), notice: 'Recipe was successfully created.'
于 2013-07-09T22:11:38.450 回答