On Tuesday, 17 June 2014 07:35:05 UTC-5, Ruby-Forum.com User wrote:
>
> I have in my model
>
> class Card < ActiveRecord::Base
> has_many :idioms, dependent: :destroy
> end
>
> class Idiom < ActiveRecord::Base
> belongs_to :card
> end
>
> In my schema, Idiom has an integer column kind. Given a certain card, I
> would like to have all associated idioms, but sorted in descending order
> according to the 'kind' column.
>
> I could do a
>
> @card.idioms.sort { .... }
>
> but would prefer doing the sorting by the time the data is retrieved
> from the database. I googled two suggestions:
>
> (1) @card.idioms(:order => 'kind DESC')
>
This doesn't seem to have any effect.
>
This doesn't do anything, because the association uses that single argument
for something different (deciding whether to reload if already loaded).
>
> (2) @card.idioms.all(:order => 'kind DESC')
>
> This gives the error "wrong number of arguments (1 for 0)".
>
> I think I could do a
>
> Idiom.where(....)
>
> and put an order restriction there, but I feel that Rails must have a
> way to specify sorting when following associations, and maybe I just
> made some silly mistake. Any ideas?
>
There are a couple ways to do this, depending on how often you need the
data sorted in a particular way:
* adding an `order` onto your relation call will order the records:
@some_card.idioms.order(kind: :desc)
* adding a scope will do the same thing:
class Idiom < ActiveRecord::Base
scope :by_kind, -> { order(kind: :desc) }
end
@some_card.idioms.by_kind
* or you can add the order directly to the association (building on the
scope above):
class Card < ActiveRecord::Base
has_many :idioms, -> { by_kind }, dependent: :destroy
end
@some_card.idioms # still sorted now
--Matt Jones
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/rubyonrails-talk/7f189a4c-6708-4cbb-aa34-f9122caac484%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.