0

I have method in my model that returns an array called all_items I'm trying to filter out the insurance item if the duration is more than 365 days so as below:

  def available_items
    return all_items - [all_items.insurance] if duration >= 365

    all_items
  end

But I'm still getting insurance even if the duration is more than 365. Tested it in the console and insurance comes up as part of the array. What did I do wrong here?

2
  • 1
    "I have method in my model" – show it, please. Since this is a Rails question I suspect that you retrieve the array from your database? If so, you'd typically use a query to specify the records you're interested in, probably via a scope. Commented Jan 8, 2020 at 16:14
  • Well, the addition with the id 28 in the one array is not the same as in the other array, they have different object ids. Where do these arrays come from? Commented Jan 8, 2020 at 16:14

3 Answers 3

1

An alternative is to simply negate your scope:

def available_items
   duration >= 365 ? Addition.where.not(id: Addition.insurance) : Addition.all
end

Though it might be more efficient to create a negative scope on your model, eg:

scope :not_insurance, -> { where.not(name: 'insurance' }

and then change the available_items to something like:

duration >= 365 ? Addition.not_insurance : Addition.all
Sign up to request clarification or add additional context in comments.

Comments

1

Addition:0x00007f8655402300 is not the same as Addition:0x00007f86526cc728

You could check the name instead of the whole object:

  def available_items
    return all_items.reject { |i| i[:name] == "insurance" } if duration >= 365

    all_items
  end

Comments

1

It looks that it is not Array but Relation and insurance is the scope.

So you can do something like

all_items.where.not(name: 'insurance')

Comments

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.