ruby on rails - Sort based on association's method -
i have method in business certified? method.
i sort quotation model using certified? method.
the return value of method boolean. sort it, have certified businesses on top of list.
here's association:
business belongs quotation
here's how now:
quotation.by_biz_id(biz.id).includes(:business).sort_by {|quote| quote.business.certified? <=> quote.business.certified? }
as can see there lots of method chaining in it. there newer , better way refactor code?
especially repeating condition: {|quote| quote.business.certified? <=> quote.business.certified?}
if remove <=> condition, error this:
argumenterror: comparison of falseclass true failed
you can use group_by instead of sorting like,
quotation.includes(:business).group_by |quote| quote.business.certified? ? "certified" : "not_certified" end it return hash containing keys certified values of certified business quotation , remaining in not_certified.
Comments
Post a Comment