2010-07-22 102 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