【问题标题】:ActionController::UrlGenerationError No route matches AND NoMethodError undefined method `accounts_lists_url' with nested resourcesActionController::UrlGenerationError 没有路由匹配和 NoMethodError 未定义方法 `accounts_lists_url' 与嵌套资源
【发布时间】:2014-10-07 21:40:25
【问题描述】:

我有一个 Rails 4.2.beta1 应用程序,我试图在成功创建新对象后返回 :show 方法。资源嵌套在以下方法中:

resources :accounts do
    resources :lists do
end

我得到的错误是:

ActionController::UrlGenerationError (No route matches {
    :account_id=>#<List id: 21, creator_id: 1, list_type_id: 1, 
                        name: "Test 16", description: nil, 
                        created_at: "2014-10-07 03:59:56", 
                        updated_at: "2014-10-07 03:59:56">, 
    :action=>"show", :controller=>"lists", :format=>nil, :id=>nil} 
    missing required keys: [:id]):

app/views/lists/show.json.jbuilder:2:in `_app_views_lists_show_json_jbuilder__4188070110312340824_70141816016640'
app/controllers/lists_controller.rb:31:in `create'

我在这里看到的是,rails 错误地认为新的 List 对象是 account_id...

这是我的create 操作:

# POST /lists
# POST /lists.json
def create
  @list = List.new(creator: @account, list_type: ListType.find(list_params[:list_type_id]), name: list_params[:name])
  if @list.save
    @account.subscriptions << @list
    render action: :show, status: :created, location: [@account, @list] and return
  end
  render json: @list.errors, status: :unprocessable_entity
end

我找到了这个 Q/A here 并遵循了那里的所有答案,结果没有变化。为了列出它们,我尝试了以下所有方法......

#1
render action: :show, status: :created, location: [@account, @list] and return

#2
render action: 'show', status: :created, location: [@account, @list] and return

#3
render action: :show, status: :created, location: [@list.creator, @list] and return

#4
render action: :show, status: :created, location: @list and return

#5
render action: :show, status: :created, location: [@list, @account] and return

#6
render action: :show, status: :created, location: [:account, @list] and return

#7
render action: :show, status: :created, location: accounts_list_url(@account, @list) and return

#8
render action: :show, status: :created and return

#9
redirect_to action: :show, status: :created, location: [@account, @list] and return

#10
redirect_to accounts_lists_url(@account, @list) and return

所有这些都会产生相同的错误(或明显的错误,例如 #5 中的 id 顺序错误)

另外需要注意的是 #7 && #10 会产生错误:

NoMethodError (undefined method `accounts_lists_url' for #<ListsController:0x007f9652235c40>)

这对我来说也很奇怪

【问题讨论】:

  • 为什么要渲染显示动作而不是重定向?
  • 您在routes.rb 中缺少一个end 关键字,或者这是一个类型?
  • @sebkomianos 是的,复制/粘贴很糟糕。其中实际上还有另一个嵌套元素...

标签: ruby-on-rails ruby-on-rails-4.2


【解决方案1】:

所以....我觉得自己像个白痴。我正在阅读错误消息,但实际上并未阅读错误消息。

问题出在我的show.json.jbuilder 文件中。我有一个account_list_url(@list) 电话,这显然是不正确的。我以为我在那里检查过,但显然没有。

带回家的消息:如果错误消息显示带有 jbuilder 的堆栈跟踪。查看jbuilder文件...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-06
    • 2016-04-29
    • 2015-09-01
    • 2015-11-26
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多