为什么simple_form会生成不存在的路由?

时间:2012-11-20 10:59:09

标签: ruby-on-rails associations simple-form

我有......

/config/routes.rb:

Testivate::Application.routes.draw do
  resources :areas do
    resources :heuristics    
  end
end

/app/models/heuristic.rb:

class Heuristic < ActiveRecord::Base
  attr_accessible :area_id
  belongs_to :area
end

/app/models/area.rb:

class Area < ActiveRecord::Base
  has_many :heuristics
end

/app/controllers/heuristics_controller.rb:

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:

%h1 New heuristic
= render 'form'
= link_to 'Back', area_heuristics_path(@area)

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

= simple_form_for @heuristic do |f|
  = f.input :foo
  = f.button :submit

我没有明确地呼叫heuristics_path,因为这当然不存在。

为什么我在http://localhost:3000/areas/1/heuristics/new收到以下错误?

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|

2 个答案:

答案 0 :(得分:5)

您可以在此处详细了解如何为嵌套资源生成网址 - http://edgeguides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects

simple_form_for [@area, @heuristic] do |f|

我认为这比url选项好。

答案 1 :(得分:3)

您使用的是嵌套路由,因此路径不会像单个资源一样。您可以运行rake routes来检查启发式资源的路径。

尝试更改:

simple_form_for @heuristic do |f|

要:

simple_form_for @heuristic, url: area_heuristics_path do |f|