在Rails中,对于这两个条件执行块:first_or_create(In Rails, execu

2019-09-22 03:27发布

任何人都知道一个Rails方法,让我去寻找现有记录或创建一个新的和执行的代码下面的方框?

例:

Model.where(parameters).first_or_create do |m|
  # execute this regardless of whether record exists or not
end

类似地,该方法find_or_create_by不会在任一场景中执行的块。

我可以使用if-else语句,但将会复制我的代码...

Answer 1:

根据该API ,如果记录不存在,在你的榜样块将只执行。 但你并不需要一个块,也不是如果其他:

m = Model.where(parameters).first_or_create
m.some_method # executes regardless of whether record exists or not

请注意,在对象上的一些验证可能失败,因此m可能尚未保存到数据库。



Answer 2:

我就捡起从一个伟大的截屏由Ryan贝茨:

Model.where(parameters).first_or_create.tap do |m|
  # execute this regardless of whether record exists or not
end

(其中User#tap选择用户),我觉得这种方式看起来干净了一点,你不必定义另一个helper方法与米沙的答案。 都工作得不错,但。



文章来源: In Rails, execute block for both conditions: first_or_create