2

对于我的应用程序,用户可以通过用户自己的显示页面上的 simple_form 创建帖子。我在需要存在的帖子模型中进行了验证。当没有输入时,我没有收到错误通知,告诉我我的字段为空白,而是 ActiveRecord::RecordInvalid, Validation failed。

我如何让它在表单上创建错误通知来告诉我一个字段是空白的?

请参阅下面的代码。

用户.rb

has_many :posts

post.rb

attr_accessible :user_id, :category
belongs_to :user
validates :category, presence: true

查看/用户/show.html.erb

<%= render 'posts/form' %>

查看/帖子/_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 %>

post_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
4

1 回答 1

3

@post = @user.posts.create!(params[:post])是问题所在。该create!方法验证您尝试创建的模型,然后在验证失败时引发异常。

你应该这样做:

@post = @user.posts.build(params[:post])

if @post.save
  # do some good stuff
else
  # do some bad stuff
end

这不会引发任何异常,并且会按照您的意愿工作。如果您想显示出现问题的消息,那么您将不得不render :new改为(例如http://blog.markusproject.org/?p=3313

于 2013-05-24T10:39:17.203 回答