如何在set上关闭has_one save?

时间:2016-06-06 23:34:07

标签: ruby-on-rails-4 has-one

在Rails中,我有一个has_one关联

func formattedPhone(phone: String) -> String?  {
    let notPhoneNumbers = NSCharacterSet.decimalDigitCharacterSet().invertedSet
    let str = phone.componentsSeparatedByCharactersInSet(notPhoneNumbers).joinWithSeparator("")

    let startIdx = str.startIndex
    let endIdx = str.endIndex

    let count = str.characters.count
    if count == 7 {
        return "\(str[startIdx..<startIdx.advancedBy(3)])-\(str[startIdx.advancedBy(3)..<endIdx])"
    }else if count == 10{
        return "(\(str[startIdx..<startIdx.advancedBy(3)]))\(str[startIdx.advancedBy(3)..<startIdx.advancedBy(6)])-\(str[startIdx.advancedBy(6)..<endIdx])"
    }
    else if count > 10{
        let extra = str.characters.count - 10
        return "+\(str[startIdx..<startIdx.advancedBy(extra)])(\(str[endIdx.advancedBy(-10)..<endIdx.advancedBy(-7)]))\(str[endIdx.advancedBy(-7)..<endIdx.advancedBy(-4)])-\(str[endIdx.advancedBy(-4)..<endIdx])"
    }
    return nil
}

当我这样做时

class Car
  has_one :driver
end

在我准备好之前,它试图保存我的司机!我只想在调用car.save

时保存驱动程序

如何使用Rails 4.2。*更改保存顺序?

2 个答案:

答案 0 :(得分:0)

我很确定它不会持续更改数据库。你可能在内存中看到它。

car.driver = driver
car.driver == driver # true
car.reload
car.driver == dirver # false

答案 1 :(得分:0)

我认为如果不调用它就无法触发保存方法。

除非您在车型中有触发它的方法,例如 autosave:true