开发者

Sorting with data from another table using sort_by ruby on rails

开发者 https://www.devze.com 2023-02-11 14:08 出处:网络
I have two models: Todo and Duedate. A Duedate has_many todos, and likewise a Todo belongs_to a Duedate. The Duedates table holds an id and a \'date\' data type entry. Every Todo object has a duedate_

I have two models: Todo and Duedate. A Duedate has_many todos, and likewise a Todo belongs_to a Duedate. The Duedates table holds an id and a 'date' data type entry. Every Todo object has a duedate_id column that corresponds to a Duedate id.

Todo has other values in it like priority and completed, which I sort by:

@todos = @todos.sort_by(&:priority)

I want to sort @todos by date, but I'm not sure how to tell sort_by to use the date associated with duedate_id in the duedate table. I can't just do

@todos = @todos.sort_by(&:duedate_id)

because that will just sort @开发者_JAVA百科todos by the date as it was entered into the duedate table, not by the date that entry corresponds to. Can anyone help?

Thanks, Ross


You're using the symbol_to_proc sugar method. You can use the plain-old block argument to sort_by:

@todos = @todos.sort_by{ |todo| todo.duedate.date }


Why do you have 2 models, why don't you just have a duedate field in your todo model?

If you had a due date field in your todo model, you could define a scope to sort your todos.

0

精彩评论

暂无评论...
验证码 换一张
取 消