Supersonic
Supersonic

Reputation: 430

Select box not prefilling when validation fail

Controller: posts_controller.rb

def post_creator
    @post = Post.new
end

def create
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render action: 'show', status: :created, location: @post }
      else
        format.html { render template: 'posts/post_creator' }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
end

Model: post.rb

class Post < ActiveRecord::Base
  validates :content, :presence => true
end

Views: post_creator.html.erb

<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.select(:name, options_for_select([['Default', 'Default'],['Test', 'Test']]),{:include_blank => 'Select Post Type'}) %>
  </div>
  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Question: When the form is submitted and the user selects a name as 'Default' from the select tag and fails to fill in the content, the validation fails and when it renders the post_creator.html.erb but the name which was already selected before is not filled, it selects Select Post Type. I have no idea Y this is happening.

Any help will be really appreciated.

Thanks

Upvotes: 0

Views: 556

Answers (1)

LHH
LHH

Reputation: 3323

Try this

<%= f.select(:name, options_for_select([['Default', 'Default'],['Test', 'Test']], :selected => params[:post][:name]),{:include_blank => 'Select Post Type'}) %>

Upvotes: 1

Related Questions