Reputation: 609
For my application, users can create posts through a simple_form on the user's own show page. I have validation in the post model that requires presence is true. When no input is made, instead of getting error notifications telling me my field is blank, I get ActiveRecord::RecordInvalid, Validation failed.
How do I get it to create error notifications on the form to tell me a field is blank?
See my code below.
user.rb
has_many :posts
post.rb
attr_accessible :user_id, :category
belongs_to :user
validates :category, presence: true
view/users/show.html.erb
<%= render 'posts/form' %>
view/posts/_form.html.erb
<p>Add Post:</p>
<%= simple_form_for([@user, @user.posts.build]) do |f| %>
<%= f.error_notification %>
<%= f.input :category %>
<%= f.submit "Add Post", :class => "btn btn-header" %>
<% end %>
posts_controller.rb
def create
@user = User.find(params[:user_id])
@post = @user.posts.build(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to user_path(@user), notice: 'Post was successful.' }
format.json { head :no_content }
else
format.html { redirect_to user_path(@user) }
format.json { render json: @post.user.errors, status: :unprocessable_entity }
end
end
end
Upvotes: 2
Views: 9307
Reputation: 1390
@post = @user.posts.create!(params[:post])
is the problem. The create!
method validates the model you are trying to create, and then raises an exception if validation fails.
You should instead do:
@post = @user.posts.build(params[:post])
if @post.save
# do some good stuff
else
# do some bad stuff
end
This won't raise any exceptions and will work as you want it to. If you want to display messages for the things that have gone wrong then you will have to render :new
instead (eg. http://blog.markusproject.org/?p=3313)
Upvotes: 3