Reputation: 1712
Instead of having to create a separate controller for nested attributes such as this:
def new
@map = @account.maps.build
end
def create
@map = @account.maps.create(params[:map].permit(:))
end
How can I pass the parameter of account_id
to the create method in the maps
controller rather than creating a whole seperate controller for accounts_maps
?
For example:
If I am creating a map under this url: http://localhost:3000/accounts/1/maps/new
I need the account_id of the map to be 1 when it is created. How can this be achieved?
Upvotes: 0
Views: 938
Reputation: 86
If you had a route defined like this in routes.rb
resources :accounts do
resources :maps
end
the url would be http://localhost:3000/accounts/17/maps, and you could access account id with
params[:account_id]
which would be 17 in this case. Also, @account.maps.build automatically adds account_id to map, what you might be missing is declaring @account.
In your example, you could do
before_action :find_account
def new
@map = @account.maps.build
end
def create
@map = Map.create(map_params)
end
private
def find_account
@account = Account.find(params[:account_id])
end
def map_params
params.require(:map).permit(:name, :account_id) #permit all map params
end
Upvotes: 1