I am trying to pass query parameter with new action http://localhost:3000/education_informations/new?user_id=10 and also set form validation on it. when form submit failed so its display error but url is changes like http://localhost:3000/education_informations so I want to same customize url and pass query parameter with user_id. Please help me
controller code give below
def create
@edu_info = EducationInformations.new(educational_params)
if @edu_info.save
#flash[:notice] = 'Vote saved.'
redirect_to @edu_info
else
render 'new'
end
end
You can pass the parameters to the form_for
like below to keep user_id
in the URL even after the form submission failed.
<%= form_for @edu_info, :url => { :action => :create, :user_id => @user.id } %>
or
<%= form_for @edu_info, :url => { :action => :create, :user_id => current_user.id } %>
If @user
is not initialised.
Source
I am supposing that the education information will always be realted to the user. So to create the route you should do as:
In routes file:
resources :users do
resources :education_informations
end
So what this will do is create the route as I specified in the comments. Like this will be routes:
user_education_informations GET /users/:user_id/education_informations(.:format) education_informations#index
POST /users/:user_id/education_informations(.:format) education_informations#create
new_user_education_information GET /users/:user_id/education_informations/new(.:format) education_informations#new
edit_user_education_information GET /users/:user_id/education_informations/:id/edit(.:format) education_informations#edit
user_education_information GET /users/:user_id/education_informations/:id(.:format) education_informations#show
PATCH /users/:user_id/education_informations/:id(.:format) education_informations#update
PUT /users/:user_id/education_informations/:id(.:format) education_informations#update
DELETE /users/:user_id/education_informations/:id(.:format) education_informations#destroy
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
So for the new eudcation information form you need to give this path new_user_education_information_path(user)
where user
will be the clicked user.
You can get more information here: http://guides.rubyonrails.org/routing.html#nested-resources
Hope this helps.
You can use redirect_to
with url parameters.
In your #create
action you will have your current user_id
params:
user_id = params[:user_id]
If you want to redirect_to
@edu_info
and keep the params, you can set them via the options hash on the redirect_to
method:
redirect_to @edu_info(user_id: user_id)
Does that make sense to you?