0

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?
0

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I think you n eed to change the syntax for plan to plan_id in the string and plan.id in the Hash. That being said Hour.find_by(term: term, hours: hours, plan_id: [nil,plan.id]) will work
@engineersmnky: Great idea, that is much better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.