Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 更好的方法是建立一个关联或更新(如果存在)_Ruby On Rails - Fatal编程技术网

Ruby on rails 更好的方法是建立一个关联或更新(如果存在)

Ruby on rails 更好的方法是建立一个关联或更新(如果存在),ruby-on-rails,Ruby On Rails,我的折扣班有销售期。我想写一个方法,当它不存在时可以建立这个关联,或者当它确实存在时更新它。目前我正在编写以下if条件 class Discount < ActiveRecord::Base has_one :sales_period def fetch_period end_date = ... if sales_period.nil? build_sales_period( end: end_date ) else sales_

我的折扣班有销售期。我想写一个方法,当它不存在时可以建立这个关联,或者当它确实存在时更新它。目前我正在编写以下if条件

class Discount < ActiveRecord::Base
  has_one :sales_period

  def fetch_period
    end_date = ...
    if sales_period.nil?
      build_sales_period( end: end_date )
    else
      sales_period.end = end_date
    end
  end
end
class折扣

有没有更好的方法,类似于
find\u或\u create

find\u或\u initialize
类似于。例:


另外,我要重命名
end
,它是一个ruby关键字。当有人试图
评估
代码或诸如此类的东西时,你可能会遇到一些奇怪的错误,这会让人非常困惑。

不完全是你想要的,但你可以稍微缩短它

def fetch_period
  end_date = ...
  period = sales_period || build_sales_period
  period.end = end_date
end

似乎当结束日期更改时,如果销售周期已经存在,它将创建一个新记录并留下一个孤立的销售周期。i、 它不会更新现有的销售期结束日期。你说得对,我误解了你的意图。我想说布拉德利的答案是正确的。也许
销售周期。按折扣id(id)查找或创建折扣。更新属性(结束:结束日期)
我认为唯一的陷阱是,它对未保存的折扣无效/我无法建立周期。我会坚持我原来的答案。谢谢,这是更好的,我认为这是最好的一个可以。是的,这取决于什么是FETCCHY周期方法实际上,但我会考虑移动这一行逻辑到它自己的方法,如果你在多个地方使用它。
def fetch_period
  end_date = ...
  period = sales_period || build_sales_period
  period.end = end_date
end