加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 更好的方法来构建has_one关联或更新(如果存在)

发布时间:2020-12-17 04:25:43 所属栏目:百科 来源:网络整理
导读:我的折扣类有一个sales_period.我想编写一个方法,可以在不存在时构建此关联,或者在它存在时更新它.目前我正在编写以下条件. class Discount ActiveRecord::Base has_one :sales_period def fetch_period end_date = ... if sales_period.nil? build_sales_pe
我的折扣类有一个sales_period.我想编写一个方法,可以在不存在时构建此关联,或者在它存在时更新它.目前我正在编写以下条件.
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

有没有更好的方法来做到这一点,类似于find_or_create?

解决方法

不是你想要的,但你可以稍微缩短它.
def fetch_period
  end_date = ...
  period = sales_period || build_sales_period
  period.end = end_date
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读