0

所以我认为这是因为我在创建时将用户 ID 合并到讨论中,因为我正在验证讨论内容和标题......

讨论模型

class Discussion < ActiveRecord::Base  
  attr_accessible :user_id, :content, :title

  has_many :discussion_comments, :dependent => :destroy
  belongs_to :user

  validate :content, :presence => true,
                     :length => {:minimum => 10, :maximum => 254}
  validate :title, :presence => true,
                   :length => {:minimum => 10, :maximum => 254}
end

讨论控制器

  def create
    @discussion = Discussion.create(params[:discussion].merge(:user_id => current_user.id))
    if @discussion.save
      redirect_to tasks_path, :flash => {:success => 'Created a new discussion'}
    else
      redirect_to tasks_path, :flash => {:error => 'Cannot create empty discussions.'}
    end
  end

无论如何,每次我尝试保存一个空表单时,它都会在应该给我错误消息时给我成功消息。

讨论表

<%= form_for @discussion do |f| %>

    <p><%= f.label :title %>
    <%= f.text_field :title %></p>

    <p><%= f.label :content %>
    <%= f.text_area :content %></p>

    <p><%= f.submit %></p>

<% end %>

如前所述,我认为这与我在创建时合并用户 ID 的事实有关,验证应该如何停止整个创建过程 - 不是吗?

4

1 回答 1

2

这是 Rails 3.x 吗?尝试使用validatesnot validate。可能只是一个简单的错字。

所以...

class Discussion < ActiveRecord::Base  
  ...

  validates :content, :presence => true,
                      :length => {:minimum => 10, :maximum => 254}
  validates :title, :presence => true,
                    :length => {:minimum => 10, :maximum => 254}
end

参考: http: //guides.rubyonrails.org/active_record_validations_callbacks.html#presence

我链接到该presence示例,但validates无论您传递给它的选项都应该是。

于 2012-09-07T14:58:50.310 回答