Ruby On Rails在模型中自我保存

时间:2021-10-27 23:47:35

I have a function in my model that changes is as follows:

我的模型中有一个函数变化如下:

  def compare
        self.dirty = 1 if self.dirty == 0
        compare_recursive(0, MergeDigestTree.all)
        self.dirty = 0;
  end

Do I have to call self.save or is it fine like this

我要打电话给赛尔夫吗?保存或者这样可以吗

3 个解决方案

#1


5  

Your question is open to two interpretations:

你的问题有两种解释:

  • Do you have to call self.save so the record is saved at this point? yes, because an attribute assignation does not commit the change to the database.

    你要打电话给赛尔夫吗?保存以便记录在此时保存?是的,因为属性指定不会将更改提交到数据库。

  • Are you obliged to call self.save and thus save the record? no. It's ok for a method to change the instance and leave open the decision whether to actually save it or not. I usually prefer this behavior, as you give more freedom to the caller.

    你有义务叫赛尔夫吗?保存并保存记录?不。对于一个方法来说,更改实例并保留决定是否保存它是可以的。我通常更喜欢这种行为,因为你给打电话的人更多的*。

Whatever the case, document the method accordingly.

无论哪种情况,都要相应地记录方法。

#2


2  

You will have to save it yourself, yes. Though I don't see what that method is really doing. :)

你必须自己保存,是的。虽然我不知道这个方法到底是怎么回事。:)

#3


1  

No, you should have to call save once changes are made, at some point after this function, if not within this function...

不,一旦做了更改,您应该在这个函数之后的某个时刻调用save,如果不在这个函数中……

so if you're using this function manually in your app...

如果你在app中手动使用这个功能…

resource.compare()
resource.save

Would be fine if you don't want to put the self.save in the compare function.

如果你不想把自我放在那里就好了。保存在比较函数中。

#1


5  

Your question is open to two interpretations:

你的问题有两种解释:

  • Do you have to call self.save so the record is saved at this point? yes, because an attribute assignation does not commit the change to the database.

    你要打电话给赛尔夫吗?保存以便记录在此时保存?是的,因为属性指定不会将更改提交到数据库。

  • Are you obliged to call self.save and thus save the record? no. It's ok for a method to change the instance and leave open the decision whether to actually save it or not. I usually prefer this behavior, as you give more freedom to the caller.

    你有义务叫赛尔夫吗?保存并保存记录?不。对于一个方法来说,更改实例并保留决定是否保存它是可以的。我通常更喜欢这种行为,因为你给打电话的人更多的*。

Whatever the case, document the method accordingly.

无论哪种情况,都要相应地记录方法。

#2


2  

You will have to save it yourself, yes. Though I don't see what that method is really doing. :)

你必须自己保存,是的。虽然我不知道这个方法到底是怎么回事。:)

#3


1  

No, you should have to call save once changes are made, at some point after this function, if not within this function...

不,一旦做了更改,您应该在这个函数之后的某个时刻调用save,如果不在这个函数中……

so if you're using this function manually in your app...

如果你在app中手动使用这个功能…

resource.compare()
resource.save

Would be fine if you don't want to put the self.save in the compare function.

如果你不想把自我放在那里就好了。保存在比较函数中。