为什么删除不适用于full_messages函数?

时间:2015-08-05 13:48:19

标签: ruby-on-rails ruby-on-rails-3 validation

我有以下代码:

def register_learner
  @event = Event.find(params[:event_id])
  @registation = EventRegistration.new first_name: params[:first_name], last_name: params[:last_name], email: params[:email], event_id: params[:event_id]

  if !@registation.valid?
    @registation.errors.full_messages.delete("Event has already been taken"
    flash[:notice] = @registation.errors.full_messages.to_sentence
    redirect_to(event_path(@event))
  else
    @registation.save
  end
end

注意我正在尝试从full_messages数组中删除此特定消息的行@registation.errors.full_messages.delete("Event has already been taken"),但它不起作用。下一行是flash消息,并且仍然显示消息“已经采取了事件”。

这是通过控制台进行的健全性检查......

2.1.5 :001 > errors = ["Event has already been taken", "Last name can't be blank"]
 => ["Event has already been taken", "Last name can't be blank"]
2.1.5 :002 > errors.delete "Event has already been taken"
 => "Event has already been taken"
2.1.5 :003 > errors
 => ["Last name can't be blank"]

我错过了什么?

2 个答案:

答案 0 :(得分:5)

这是因为full_messages是一种方法,每次调用它时都会生成一个新数组。做你想做的事:

errors = @registation.errors.full_messages
errors.delete("Event has already been taken")
flash[:notice] = errors.to_sentence

这回答了这个问题,现在有一个问题 - 为什么你需要这样做?可能有更好的方法。

一般来说,依赖字符串通常是一个坏主意,想象一下,在半年之内,您需要更改此验证的错误消息。你能100%确定你会记得在这里改变它吗?如果没有,你有一个错误。

答案 1 :(得分:0)

好吧,因为每次调用方法时Rails都会使用string saveDir = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory("the_projectB_defaultDirectory"); ProjectBfunction() ; Directory.SetCurrentDirectory(saveDir) ; 重新创建#full_messages

errors

Source

您可以使用def full_messages(options = {}) @errors.values.inject([]) do |full_messages, errors| full_messages + errors.map { |error| error.full_message } end end 跳过该消息:

#select

此外,您可以在@registation.errors.full_messages.select{|x| x != "Event has already been taken"}.to_sentence (而非#delete)上使用#errors.messages,因为它们是基础对象的公开属性(不是副本,与full_messages一样):

full_messages