使用Ruby on Rails模型按A然后B排序

时间:2016-07-28 02:18:52

标签: ruby-on-rails ruby sorting activerecord

这不是一个家庭作业问题。我想了解更多。

我有以下具有属性
的实体 Manufacturer {name} //存储制造商
Model {manufacturer_id, name} //商店模型
Tint {manufacturer_id, model_id, front, side, rear} //存储测量值

我的Tint实体中包含以下数据。字母代表不同的制造商名称和型号。

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   |

当我在view打印出来时,我希望根据Manufacturer名称然后Model对其进行排序。所以结果如下。制造商的名称将按字母顺序排序,然后是模型。

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   |

我已设置模型以确保ManufacturerModel是一对独特的值。

我的问题是,由于我使用manufacturer_idmodel_id引用,如何从Manufacturer和{Model获取ManufacturerModel的名称{1}}表。

在我的tints_controller.rb中,我有@tints = Tint.all.order(:manufacturer_id)。但是,它只会根据manufacturer_id(如数字)而不是制造商的名称进行排序。

我知道我可以在RoR模型中以SQL方式(SELECT, FROM, WHERE)执行此操作。但是,我想知道是否可以使用ActiveRecord根据名称对数据进行排序。

4 个答案:

答案 0 :(得分:2)

如果我理解正确,你有3个型号,Tint,Manufacturer和Model。我假设您正确设置了适当的has_many和belongs_to associations

Tint.rb
belongs_to :workspace

Manufacturer.rb
has_many :models
has_many :tints,  through: :models

Model.rb:
belongs_to Manufacturer
has_many :tints

您需要先将三个模型连接在一起,然后按一些标准排序

tints_controller.rb
@tints = Tint.joins(model: :manufacturer).order('manufacturers.name, models.name').pluck('manufacturers.name, models.name, tints.front, tints.side, tints.rear')

这将为您提供所有色调记录,并且他们适合模型和制造商。

答案 1 :(得分:0)

只要你在Rails中拥有id实体,只需通过实例化该实体就可以轻松检索其他相关字段:

@manufacturer = Manufacturer.find(params[manufacturer_id])

然后检索任何其他字段是一件简单的事情:

@manufacturer_name = @manufacturer.name

如果您需要制造商或制造商名称的集合,那么建议您立即通过范围查询(如您所知)自己构建ActiveRecord::Relation对象。我不知道你的标准是什么,否则,我会提供一些示例代码。我可以告诉你,你的范围查询最后应该包含一个.order子句:

@manufacturers = Manufacturer.where("some_column = ?", some_criterion).order(:sort_field)

在上面的示例中,:sort_field将是您想要对ActiveRecord::Relation进行排序的字段。我猜你的情况是:name

所有这些都被说过,如果你想要花哨的排序表,你应该看看JQuery DataTables宝石。 DataTables可以为您做很多繁重的工作,对您的用户来说非常方便,因为他们可以根据您提供的任何列进行排序和求助。

答案 2 :(得分:0)

在你的tints_controller.rb中,

的instedad
@tints = Tint.all.order(:manufacturer_id)

请写下:

@tints = Tint.all.order(:manufacturer_id, :model_id) 

答案 3 :(得分:0)

回答我的问题:

tints_controller.rb,我写道 @tints = Tint.joins(:manufacturer, :model).order("manufacturers.name ASC, models.name ASC")加入表格并相应地订购。

我尝试了上面@Goston提供的答案,当我尝试编辑tints时遇到了问题。它不允许我编辑。

注意:@Goston提供的答案会对它们进行排序,但它打破了edit功能。

相关问题