0

比较两个字符串表达式"batman" != "batman"时无法创建对象,但是当"batman" != "robin"它成功创建对象时,发生了什么?

class WebsiteLink < ActiveRecord::Base
  attr_accessible :external

  before_save :external?


  private
  def external?
    if "batman" != "batman"
        self.external = true
    else
        self.external = false
    end
  end
end
4

1 回答 1

2

如果 abefore_filter返回false,则过滤器链停止。由于 Ruby 返回最后一个表达式的返回值(self.external =在您的示例中)save,因此如果您分配falseself.external.

顺便说一句:self.external = "batman" != "batman"比:

if "batman" != "batman"
  self.external = true
else
  self.external = false
end

因此,如果您希望您的示例即使external分配为 false 也能正常工作,您需要true显式返回:

class WebsiteLink < ActiveRecord::Base
  attr_accessible :external

  before_save :determine_external

private
  def determine_external
    self.external = "batman" != "batman"
    true
  end
end
于 2013-09-28T16:37:19.483 回答