在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 / views / properties / _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 %>
在app / views / properties / new.html.erb中:
<h1>New property</h1>
<%= render 'form' %>
<%= link_to 'Back', @property %>
我怀疑未定义的properties_path错误与代理商下属性资源的嵌套有关。但是,我无法弄清楚如何处理_form.html.erb第1行中的抱怨,因为像form_for (@agency, @property)
这样的东西不起作用。
有什么想法吗?
答案 0 :(得分:2)
根据您的路线,财产是否代理机构,对吗?
为避免错误,您可以按照以下方式:
step1-在控制器中,在'new'动作中,将@property对象实例化为:
@property = Property.new(:agency_id => params[:agency_id]) # this will have agency association from beginning
_form.html.erb中的step2-使用此:
form_for (@property.agency,@property)
此代码应该可以肯定(我经常使用它),不知道是否有更清洁/更难看的解决方案;)