字符串比较rails中的before_save

时间:2013-09-28 16:26:25

标签: ruby-on-rails ruby

比较两个字符串表达式"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

1 个答案:

答案 0 :(得分:2)

如果before_filter返回false,则过滤器链会停止。由于Ruby返回最后一个表达式的返回值(在您的示例中为self.external =),如果您将save分配给false,则不会发生self.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