ネストされたモデルフォームが機能していますが、ビューにデータを表示する際に問題があります。 1対多の関係でネストされたモデルデータを表示するにはどうすればよいですか?どんな助けでも大歓迎です。ここでネストされたモデルを表示する
は私のフォームとコントローラです:1対多の関係が存在するとき、一般的に
<%= 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句"の型を持つ子を指定する必要がありますか?
ここでは、作成したばかりのOrganizationの名前を表示しようとしているshow.html.erbという簡単な例を示します。それは動作しません。
<h1><%= @organization.name %></h1>
このエラーで上記フォームの結果でアカウントを作成した後は、「show」アクションをレンダリング:
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"}
あなたのショーアクションのコントローラコードも投稿できますか? – Msencenb
あなたは 'redirect_to ... 'ではなく、あなたの作成アクションで' render show'をやっているでしょう。ですから、コントローラコードを教えてください。 – Mischa