Rails方法执行,什么时候不应该?

时间:2016-12-21 22:31:23

标签: ruby-on-rails

rails 3.2

在我的tickets_controller中,我有以下内容:

def update
  @ticket = Ticket.find params[:id]
  authorize! :update, @ticket
  @ticket.assign_attributes(params[:ticket])
  @ticket.customer_info.company = @ticket.customer if @ticket.customer_info
  @ticket.admin_context = true
  if !params[:ticket_update_type].nil? && params[:ticket_update_type] == 'save_lead_billing'
    @ticket.process_lead_billing params
  end
  if @ticket.save
    @ticket.update_attribute(:ticket_type, @ticket.ticket_profile.ticket_type)
    redirect_to [:admin, @ticket], notice: success_message
  else
    @ticket.customer_info_type = 'existing'
    @can_update_ticket = can? :update, @ticket
    @tag_groups = TagGroup.with_type('ticket').for_company(@ticket.customer_id)
    flash.now[:error] = @ticket.errors.full_messages.join(', ')
    render action: "show"
  end
end

在我的ticket.rb模型中,我有以下内容:

def process_lead_billing params
  if params[:lead_billing]["pre_tax_total"].nil? || params[:lead_billing]["post_tax_total"].nil?
    return
  end
  # handles case where billing infor has not been added to lead ticket
  if params[:ticket_update_type] == "save_lead_billing"
    lead_billing = LeadBilling.new(
        :ticket_id => self.id,
        :pre_tax_total => params[:lead_billing]["pre_tax_total"],
        :post_tax_total => params[:lead_billing]["post_tax_total"],
        :status => 'entered'
    )
    lead_billing.save!
  end

结束

在lead_billing.rb模型中,我有以下内容:

class LeadBilling < ActiveRecord::Base
  validates_presence_of :pre_tax_total, :post_tax_total
  validates_numericality_of :pre_tax_total, greater_than: 0, allow_blank: false, only_integer: false
  validates_numericality_of :post_tax_total, greater_than_or_equal_to: :pre_tax_total, allow_blank: false, only_integer: false    

问题是,当提交表单时,pre_tax_total和post_tax_total为空,我收到一条错误消息。

从日志文件中:

Started PUT "/admin/tickets/163812" for 73.83.66.151 at 2016-12-21 22:05:28 +0000
Processing by Admin::TicketsController#update as HTML

并且参数是:

[utf8] => ✓
[authenticity_token] => mNt+aI3YInoutup4UsBGZ8zZkeFRYCBZAsxEv4JPvoE=
[ticket] => Array
    (
         ......
    )

[time_span] => 
[city] => Draper
[state] => Utah
[admin] => true
[specialty] => 
[services] => 
[inventories] => 
[ticket_update_type] => save_lead_billing
[ticket_id] => 1480720184_0388234_ticket
[lead_billing] => Array
    (
        [pre_tax_total] => 
        [post_tax_total] => 
    )

[id] => 163812

从日志文件中,错误是:

Validation failed: Pre tax total can't be blank, Pre tax total is not
a number, Post tax total can't be blank, Post tax total is not a number from    

然后它指向ticket_controller.rb中的行,其中正确调用processing_lead_billing方法,然后指向processing_lead_billing方法中的行,该行尝试保存潜在客户结算。

当我检查nil时,执行应该已经停止,但是它继续执行。有任何想法吗?

1 个答案:

答案 0 :(得分:1)

Rails有空白吗?测试形式参数时通常首选的方法。

零?是一个ruby方法,只有当对象为nil时才返回true,而空白?涵盖了各种用例(空字符串,空数组,空字典,当然还有nil值)。

在你的情况下,给出rails如何工作,返回的值很可能是空字符串,所以你应该测试空白?而不是零?。