Search code examples
ruby-on-railsnested-resources

How can I create an account resource with default parameters at the same time as creating a user resource?


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.


Solution

  • 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.