简体   繁体   中英

Rails 4: Params not passed back to view after form submission

I have a basic form for creating a project...

<%= form_for(@project, :url => {:action=>'create'}) do |f| %>
<%= f.text_field(:name, {class: "form-control"}) %>
<%= f.text_area(:instructions, {class: "form-control"}) %>
<%= f.submit('Create Project') %>
<% end %>

In the controller, I have two actions:

  def create
    @project = Project.new( project_params )
    if @project.save
        flash[:notice]= "New project created!"
        redirect_to(:action=>'index')
    else
      flash[:error]="Problem creating project"
      redirect_to(:action=>'new')
    end
  end

  def new
    @project = Project.new()
  end

I have a couple validations which prevent the fields from being empty. When the form fails, I get redirected back to the "new" page again, but the @project variable is always empty.

Why?

You don't want to redirect on an error, you want to render: doing so means the new page will be rendered with variables from (and the URL of) the create action, pre-populating your form fields as you would expect.

Change your controller action to this:

def create
    @project = Project.new( project_params )
    if @project.save
        flash[:notice]= "New project created!"
        redirect_to(:action=>'index')
    else
      flash[:error]="Problem creating project"
      render :new
    end
  end

更改redirect_to(:action=>'new')render 'new'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM