2010-07-22 135 views
1

在Rails 3缘,我已经建立了两个嵌套的资源是这样的:Rails 3个中嵌套资源未定义的方法错误

config/routes.rb 

resources :agencies do 
    resources :properties 
end 

我用Mongomapper作为我的ORM,当我尝试创建下一个新的属性现有的代理,我得到这个错误:

---> http://localhost:3000/agencies/4c3ff0f455899f0fb5000001/properties/new 

NoMethodError in Properties#new 

Showing /Users/peter/programming-MacBookPro/iPhone/inspector-on-rails/app/views/properties/_form.html.erb where line #1 raised: 

undefined method `properties_path' for #<#<Class:0x00000100dae020>:0x00000100d97f00> 
Extracted source (around line #1): 

1: <%= form_for @property do |f| %> 
2: <% if @property.errors.any? %> 
3: <div id="error_explanation"> 
4:  <h2><%= pluralize(@property.errors.count, "error") %> prohibited this property from being saved:</h2> 
Trace of template inclusion: app/views/properties/new.html.erb 

Rails.root: /Users/peter/programming-MacBookPro/p-on-rails 

Application Trace | Framework Trace | Full Trace 
app/views/properties/_form.html.erb:1 
app/views/properties/new.html.erb:3 
app/controllers/properties_controller.rb:29:in `new' 
Request 

Parameters: 

{"agency_id"=>"4c3ff0f455899f0fb5000001"} 

在properties_controller.rb:

def new 
    @property = Property.new 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render :json => @property } 
    end 
end 
在app

/图S /属性/ _form.html.erb:

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

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

在应用程序/视图/属性/ new.html.erb:

<h1>New property</h1> 
<%= render 'form' %> 
<%= link_to 'Back', @property %> 

我怀疑有关properties_path没有被定义的错误有某事在机构下嵌套房地产资源。但是,我无法弄清楚如何处理_form.html.erb的第1行中的投诉,因为form_for (@agency, @property)之类的内容不起作用。

任何想法?

回答

2

根据您的路线,财产是嵌套在代理机构,对不对?

,以避免错误,你可以按照这种方式:在控制器

step1-,在 '新' 行动,实例@property对象为:在_form.html.erb

@property = Property.new(:agency_id => params[:agency_id]) # this will have agency association from beginning 

step2-使用此:

form_for (@property.agency,@property) 

这个代码应该是肯定的工作(我用它经常),不知道是否有一个更清洁/丑少的解决方案;)

+0

谢谢,这工作。我还发现,还会生成各种url助手,如edit_agency_property_path(@agency,@property)等。感谢您的帮助。 – futureshocked 2010-07-23 02:33:11