Melvin Ch'ng Melvin Ch'ng - 4 months ago 8
Ruby Question

Order by A then B using Ruby on Rails Model

This is not a homework question. I am trying to learn more.

I have the following entities with attributes

Manufacturer {name}
//Store Manufactueres

Model {manufacturer_id, name}
//Store Models

Tint {manufacturer_id, model_id, front, side, rear}
//Store measurements


I have the follow data in my
Tint
entity. Alphabets stands for different manufacturer name and models.

Manufacturer | Model | Front | Side | Rear |
-------------+-------+-------+------+-------
A | AD | 10 | 10 | 10 |
B | AB | 10 | 10 | 10 |
A | AA | 10 | 10 | 10 |
A | AC | 10 | 10 | 10 |
B | AA | 10 | 10 | 10 |
A | AB | 10 | 10 | 10 |


When I print it out in
view
, I would like to have it sorted based on
Manufacturer
name and then
Model
. So the result will be as below. The name of the Manufactures will be sorted alphabetically, then Models.

Manufacturer | Model | Front | Side | Rear |
-------------+-------+-------+------+-------
A | AA | 10 | 10 | 10 |
A | AB | 10 | 10 | 10 |
A | AC | 10 | 10 | 10 |
A | AD | 10 | 10 | 10 |
B | AA | 10 | 10 | 10 |
B | AB | 10 | 10 | 10 |


I have setup the model to make sure
Manufacturer
and
Model
is a distinct pair of values.

My question is since I am referencing using
manufacturer_id
and
model_id
, how can I get the name of the
Manufacturer
and
Model
from
Manufacturer
and
Model
table.


In my tints_controller.rb, I have
@tints = Tint.all.order(:manufacturer_id)
. However, it will only sort based on the
manufacturer_id
(as in numbers) instead of the name of the manufacturer.

I know that I can do it in SQL way
(SELECT, FROM, WHERE)
in RoR model. However, I would like to know is it possible to use ActiveRecord to sort the data based on their name.

Answer

Answer to my question:

In tints_controller.rb, I wrote @tints = Tint.joins(:manufacturer, :model).order("manufacturers.name ASC, models.name ASC") to join the table and order them accordingly.

I tried the answer provided by @Goston above and I had an issue when I was trying edit the tints. It did not allow me to edit.

Note: Answer provided by @Goston will order them, but it broke the edit function for my case.