On Jul 14, 2005, at 6:36 PM, Jeff Casimir wrote:
> Hey all,
>
> I would really like to use sort_by to sort some of my records.
> However, many of the rows have a null value for this column. From
> a pure data model, this is the value that "makes sense" in those
> cases, so modifying the DB schema (like having a default of 0 or -1
> or something) is not ok.
>
> Imagine the table looking something like this:
>
> Columns: [id,parent,text]
> row1: [1,null,"text"]
> row2: [2,null,"text"]
> row3: [3,1,"text"]
>
> I want to be able to perform a function like:
>
> model_name.sort_by(|model| model.parent)
>
> This doesn''t work because it chokes on the null values for the
> parent field of rows 1 and 2.
How would you like nulls sorted? One way is to do something like:
model_name.sort_by { |model| model.parent || 0 }
so that if a field is null, it is compared as if it were 0.
- Jamis