Reputation: 538
I want to be able to use the ID present in the route
post 'users/:id/contacts/create' => 'contacts#create'
. I am trying to parse the ID by params[:id]
. As shown below, in my contact controller:
def create
@contact = Contact.new(contact_params)
if @contact.save
render json: @contact, status: :created, location: @contact
else
render json: @contact.errors, status: :unprocessable_entity
end
end
The contact params function is:
def contact_params
params.require(:contact).permit( :name, :email, :phone, :user_id=>params[:id])
end
However, when I am posting the data, the :user_id is returning as null.
Upvotes: 0
Views: 82
Reputation: 1923
Please try this:
def contact_params
params[:contact][:user_id] = params[:id]
params.require(:contact).permit( :name, :email, :phone, :user_id )
end
Upvotes: 2
Reputation: 3962
Maybe you want to change the id parameter route to nested because it is not the primary object/resource of the ContactsController
resources :users do
resources :contacts, as: 'users_contacts'
end
Then run bundle exec rake routes CONTROLLER=users
Should print how its setup.
I think your parameters should then appear as you want them
params.require(:contact).permit( :name, :email, :phone, :user_id)
Remember you also want to do this so as to follow the rails way. Any deviation from standard way will make things complex unnecessarily in future.
As a suggestion try generating a default scaffold controller with routes done like that.
rails g scaffold_controller Contacts
That should have this object saved via post in the code and a sneak peak at the parameters.
Hope it helps.
Upvotes: 1