Fabíola Magossi
Fabíola Magossi

Reputation: 39

Ruby and Rails conditional (value is null OR some value)

I'm using Ruby 2.4 and rails 5.1.7

I want to assign variable value with conditional if plan x = plan x OR plan is null.

For example, my original table will return these results:

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

And I need result to be like this:

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

Can I use something like plan || plan.blank? for this?

     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?

Upvotes: 0

Views: 153

Answers (1)

spickermann
spickermann

Reputation: 106882

You could is another query syntax and be explicit:

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

Note that I change the query to find_by because find_or_create_by does not really make sense when an attribute can have two starts (plan or be nil). What value should the new instance have (plan or be nil)?

That said I would write that line as:

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

Upvotes: 4

Related Questions