我的嵌套模型表单现在正在工作,但我在显示视图中的数据时遇到了问题。如何显示具有一对多关系的嵌套模型数据?任何帮助将不胜感激。显示嵌套模型
这里是我的形式和控制器:
<%= form_for @account do |f| %>
<%= f.label :account_type %><br />
<%= f.text_field :account_type %><br />
<%= f.fields_for :organizations do |builder| %>
<%= builder.label :name %><br />
<%= builder.text_field :name %><br />
<%= builder.label :website %><br />
<%= builder.text_field :website %><br />
<%= builder.fields_for :locations do |lb| %>
<%= lb.label :phone %><br />
<%= lb.text_field :phone %><br />
<%= lb.label :toll_free_phone %><br />
<%= lb.text_field :toll_free_phone %><br />
<%= lb.label :fax %><br />
<%= lb.text_field :fax %><br />
<%= lb.fields_for :addresses do |ab| %>
<%= ab.label :address1 %><br />
<%= ab.text_field :address1 %><br />
<%= ab.label :address2 %><br />
<%= ab.text_field :address2 %><br />
<%= ab.label :city %><br />
<%= ab.text_field :city %><br />
<%= ab.label :state %><br />
<%= ab.text_field :state %><br />
<%= ab.label :zip %><br />
<%= ab.text_field :zip %><br />
<% end %>
<% end %>
<% end %>
<%= f.submit "Add account" %>
<% end %>
class AccountsController < ApplicationController
def show
@account = Account.find(params[:id])
@organization = @account.organizations
end
def new
@account = Account.new
organization = @account.organizations.build
location = organization.locations.build
location.addresses.build
@header = "Create account"
end
def create
@account = Account.new(params[:account])
if @account.save
flash[:success] = "Account added successfully"
render 'show'
else
render 'new'
end
end
end
在一般情况下,我如何引用嵌套模型数据的视图时,有一个一对多的关系?我是否需要使用某种类型的“where子句”来指定孩子?
下面是一个简单的示例show.html.erb,我尝试显示刚创建的组织的名称。它不起作用。
<h1><%= @organization.name %></h1>
渲染“秀”的行动与上述形式导致此错误创建一个帐户后:
NoMethodError in Accounts#create
Showing C:/Documents and Settings/Corey Quillen/My
Documents/rails_projects/shop_manager/app/views/accounts/show.html.erb where line #1
raised:
undefined method `name' for nil:NilClass
Extracted source (around line #1):
1: <h1><%= @organization.name %></h1>
Rails.root: C:/Documents and Settings/Corey Quillen/My
Documents/rails_projects/shop_manager
Application Trace | Framework Trace | Full Trace
app/views/accounts/show.html.erb:1:in
`_app_views_accounts_show_html_erb__790921876_14235864__946051513'
app/controllers/accounts_controller.rb:21:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"y59rGAhS+kqfH3v3axhlYuxvBbBxIWXg0yucCFwfBq8=",
"account"=>{"account_type"=>"dfdf",
"organizations_attributes"=>{"0"=>{"name"=>"dfdf",
"website"=>"dfdf",
"locations_attributes"=>{"0"=>{"phone"=>"dfdf",
"toll_free_phone"=>"dfd",
"fax"=>"",
"addresses_attributes"=>{"0"=>{"address1"=>"",
"address2"=>"",
"city"=>"",
"state"=>"",
"zip"=>""}}}}}}},
"commit"=>"Add account"}
您是否也可以为您的show动作发布控制器代码? – Msencenb
您可能正在执行'render show'而不是'redirect_to ...'。所以,是的,请向我们展示您的控制器代码。 – Mischa