Justin
Justin

Reputation: 4940

Rails sort posts by Category

After doing my due diligence online and elsewhere, I'm still having trouble sorting my posts (view and controller) based on their category.

I have three models: Design, Category, and Type.

Design.rb

belongs_to :type

Category.rb

has_many :designs
has_many :types, :order => "name"

Type.rb

belongs_to :category
belongs_to :design

If something needs to be changed here, please shed light to that.

After starting this search to find the answer to sort posts, I came across another problem that I'll ask in another question but will disclose here just in case. In the Command Line, if I search for a category, I get the category but also the warning:

DEPRECATION WARNING: The following options in your Category.has_many :types declaration are deprecated: :order. Please use a scope block instead.

and when I search for a Type I get this warning:

DEPRECATION WARNING: Using #scope without passing a callable object is deprecated. For example `scope :red, where(color: 'red')` should be changed to `scope :red, -> { where(color: 'red') }`.

Anyway, in my current app, the categories are men and women and the types include accessories, shirts, tops, jackets, etc and so on. When a user created a design, they have a select to choose the type that has headings like this:

Men
  Accessories
  Jackets
  etc
Women
  Accessories
  Dresses
  etc

In my view, I want the user to be able to sort the posts by men or women (Category) and also even further by Type, like Women's Accessories or Men's Accessories

Both Category and Type's can be found by either their ID or a string.

If I can provide anything else to help, please let me know and I'll include as much as I can. Thanks.

Upvotes: 0

Views: 1273

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124419

In Rails 4, you pass conditions to a has_many, belongs_to, etc. in a block:

has_many :types, -> { order("name") }

Then, when the association is accessed, that block will be called on the association, e.g.:

my_category.types

# would return the same result as
my_category.types.order("name")

Upvotes: 3

Related Questions