DEV Community 👩‍💻👨‍💻

gaaamii
gaaamii

Posted on

Rails tips: Render :new with previous query params

When writing forms with Rails, it's common to use render :new for errors of validation. With render :new, unlike redirect_to, you can show a new page again without reset of form values. It's pretty useful in the aspect of UX.

#create action is like:

def create
  if @foo.save
    redirect_to foos_index_path
  else
    render :new
  end
end

However, when query params is specified at a new page , there is an issue. After rendering of new page, query params will disappear. How can I hold query params to the second time new page?

It's possible by giving query params to forms.

If its new page's form is like below:

= form_for @foo, url: sign_in_path do |f|
  / ...

Just give a query param to path helper method.

= form_for @foo, url: sign_in_path(query: @query) do |f|
  / ...

@query is passed by controller's #new action.

def new
  @query = params[:query]
end

It worked fine for me.

Top comments (0)

Take Your Github Repository To The Next Level

>> Check out this classic DEV post <<