Rails and Select
Rails and select
In a rails project I’m working on I was trying to select from the database some sales with some conditions.
To start the
Sale model has multiples associations .
1 2 3 4 5 6
So the goal of this select was to obtain all the
Sales where the
LineItems has express_checkout set it to true.
I thought it was easy, in the
Sales controller I will get all the sales
Sales.all do a select
Sales.all.select that’s the easy part, inside the block is were
I got lost, because I have access to sale not the line_items associated to it, I started trying to fetch the line_items and perform another
1 2 3 4 5
So I see this code and thought that must be right, but I keep getting all the
A friend of mine told to extract a method for this kinf of task in the
Salesmodel, so I gave it a try, and created a new method call express_checkout?.
This method did basically the same but instead I store the result of the select in a variable and then check if there where any object inside that variable.
That approach worked.
So my thoughts were inside the select always will return an array with the elemnts that passed from the condition, but I didn’t know we have to store them in a variable and then check it.
The final code:
1 2 3 4