1

Apologize for the easy question.

I have nested resources

 resources :users do
  resources :accounts
 end

and I want to have an account for a new user create in the background when a user is created.

I tried

UserController

def create
    @user = User.new(params[:user])
    @account = Account.new(params[:account])
end

form_for User

<%= form_for([@user, @account]) do |f| %>
. . . 
<%= f.submit %>

But I get this error

 No route matches {:action=>"new", :controller=>"accounts"}

I also want to pass default data in the account. "e.g. balance_in_cents => 0, etc"

Thanks for any help y'all can provide.

ajbraus
  • 2,909
  • 3
  • 31
  • 45

2 Answers2

0

If your user has_many accounts, in your create method in the controller you should have @account = @user.accounts.build. This will then build an account for that user.

This railscast is very useful for nested forms and the rails guide for associations is here.

Edward
  • 3,429
  • 2
  • 27
  • 43
  • putting in your solution I got: _No association found for name `users'. Has it been defined yet?_ – ajbraus Apr 17 '12 at 02:50
  • adding **@account = @user.accounts.create** the error I get now is that _the parent (@user) must be saved before calling create on the account._ – ajbraus Apr 17 '12 at 02:51
  • In your user model you need to have has_many accounts In your account model you need to have belongs_to user – Edward Apr 17 '12 at 08:15
  • I have that already. I've rake db:migrate'd and now the error I get when I create a user is _No association found for name `users'. Has it been defined yet?_ – ajbraus Apr 18 '12 at 22:54
0

Your form_for is not generating the correct route. It often gets confused about the HTTP method. What you need is

<%= form_for([@user, @account], :url => users_path, :method => :post) do |form| %>
Marlin Pierce
  • 9,931
  • 4
  • 30
  • 52