【问题标题】:Ruby and Rails conditional (value is null OR some value)Ruby 和 Rails 条件(值为 null 或某个值)
【发布时间】:2021-07-14 18:02:33
【问题描述】:

我正在使用 Ruby 2.4 和 rails 5.1.7

如果计划 x = 计划 x 或计划为空,我想用条件分配变量值。

例如,我的原始表格将返回这些结果:

plan       term     hours
A          4         60
(nul)      2         60
(nul)      3         60
B          5         60
A          6         60

我需要这样的结果:

plan       term     hours
A          2         60
A          3         60
A          6         60
B          2         60
B          3         60
B          5         60

我可以为此使用plan || plan.blank? 之类的东西吗?

     courses.each do |course|
        if course.code.any?
          curriculum = course.code.find_by(code: code)
          next if code.blank?
          term = terms.find_by(order: term.to_i)
          plan = Plan.find_by(course: course, title: plan_title)
          Hour.find_or_create_by(
            term: term,
            hours: hours,
            plan: plan || plan.blank?

【问题讨论】:

    标签: ruby-on-rails ruby conditional-statements


    【解决方案1】:

    你可以是另一种查询语法并且是明确的:

    Hour.find_by(term: term, hours: hours, plan_id: [plan.id, nil])
    

    请注意,我将查询更改为 find_by,因为当属性可以有两个开始时(plannil),find_or_create_by 并没有真正意义。新实例应该具有什么值(plannil)?

    也就是说我会把那行写成:

    Hour.find_by(term: term, hours: hours, plan_id: [plan.id, nil]) ||
      Hour.create(term: term, hours: hours, plan: plan)
    

    【讨论】:

    • 我认为您需要将字符串中的plan 的语法更改为plan_idHash 中的plan.id。话虽如此,Hour.find_by(term: term, hours: hours, plan_id: [nil,plan.id]) 会起作用
    • @engineersmnky:好主意,这要好得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    相关资源
    最近更新 更多