重定向上的Url Generation错误

时间:2013-07-09 18:26:17

标签: ruby-on-rails ruby

我有一个基本的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错误,但我不知道为什么。

感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

把它放在你的创作和放大器中更新方法:

redirect_to recipe_path(username: current_user.username, id: @recipe.id), notice: 'Recipe was successfully created.'