首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么simple_form生成一个不存在的路由?

为什么simple_form生成一个不存在的路由?
EN

Stack Overflow用户
提问于 2012-11-20 10:59:09
回答 2查看 2.5K关注 0票数 1

我有。

/config/routes.rb:

代码语言:javascript
复制
Testivate::Application.routes.draw do
  resources :areas do
    resources :heuristics    
  end
end

/app/models/heuristic.rb:

代码语言:javascript
复制
class Heuristic < ActiveRecord::Base
  attr_accessible :area_id
  belongs_to :area
end

/app/models/area.rb:

代码语言:javascript
复制
class Area < ActiveRecord::Base
  has_many :heuristics
end

/app/controllers/heuristics_controller.rb:

代码语言:javascript
复制
class HeuristicsController < ApplicationController
  def new
    @area = Area.find(params[:area_id])
    @heuristic = @area.heuristics.build
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @heuristic }
    end
  end
end

/app/views/heuristics/new.html.haml:

代码语言:javascript
复制
%h1 New heuristic
= render 'form'
= link_to 'Back', area_heuristics_path(@area)

/app/views/heuristics/_form.html.haml:

代码语言:javascript
复制
= simple_form_for @heuristic do |f|
  = f.input :foo
  = f.button :submit

在任何时候,我都不会显式地调用heuristics_path,因为这当然不存在。

为什么我会在http://localhost:3000/areas/1/heuristics/new上得到以下错误

代码语言:javascript
复制
NoMethodError in Heuristics#new
Showing /Users/steven/Dropbox/testivate/app/views/heuristics/_form.html.haml where line #1 raised:
undefined method `heuristics_path' for #<#<Class:0x007fea3b2ac1a0>:0x007fea3d027608>
Extracted source (around line #1):
1: = simple_form_for @heuristic do |f|
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-11-20 13:32:16

您可以在这里阅读有关为嵌套资源生成urls的更多信息- http://edgeguides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects

代码语言:javascript
复制
simple_form_for [@area, @heuristic] do |f|

我认为这比url的选择要好。

票数 5
EN

Stack Overflow用户

发布于 2012-11-20 11:28:44

您使用的是嵌套路由,因此路径将不喜欢作为单个资源。您可以运行rake routes来检查启发式资源的路径。

试着改变:

代码语言:javascript
复制
simple_form_for @heuristic do |f|

至:

代码语言:javascript
复制
simple_form_for @heuristic, url: area_heuristics_path do |f|
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13471750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档