I have a nested model structure that looks like this:
resources :users, :path => '/' do
resources :accounts do
resources :characters
end
end
I'm trying to get the accounts#new
page to show both the forms but for some reason only the accounts form is displayed (screenshot).
Here's the git: https://github.com/imjp/d2shed
account.rb
class Account < ActiveRecord::Base
attr_accessible :account_name, :realm
accepts_nested_attributes_for :characters
belongs_to :user
has_many :characters, :dependent => :destroy
validates :account_name, :presence => 'true',
:length => { :in => 4..20 },
:uniqueness => 'true'
validates_presence_of :realm
validates_format_of :account_name, :with => /^[A-Za-z\d_]+$/
end
accounts_controller.rb
def new
@user = User.find(params[:user_id])
@account = Account.new
@account.characters.build
end
_form.html.erb
<%= form_for([@user, @account]) do |f| %>
<div class="field">
<%= f.label :account_name %><br />
<%= f.text_field :account_name %>
</div>
<div class="field">
<%= f.radio_button(:rea开发者_运维技巧lm, "USWest") %>
<%= f.label(:realm, "USWest") %>
<%= f.radio_button(:realm, "USEast") %>
<%= f.label(:realm, "USEast") %>
<%= f.radio_button(:realm, "Europe") %>
<%= f.label(:realm, "Europe") %>
<%= f.radio_button(:realm, "Asia") %>
<%= f.label(:realm, "Asia") %>
</div>
<%= f.fields_for :character do |character_form| %>
<div class="field">
Name: <%= character_form.text_field :name %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
EDIT: The code works now!
Why are you doing fields_for ".."
?
What you want to do is <%= f.fields_for :characters %>
as that will iterate through all the characters and render the fields as required in the account form. By calling fields_for
on the f
object you're telling the parent form that it contains nested attributes.
Secondly, you'll need to use the @account
object in your form rather than building another one with @user.accounts.build
. By doing it this wrong way, you're actually creating a new account object which wouldn't have any character objects pre-built for it.
In addition to this you will need to specify accepts_nested_attributes_for :characters
in your Account
model so that the form accepts them along with the account parameters.
精彩评论