【发布时间】:2014-06-11 10:19:01
【问题描述】:
我正在对具有来自两个不同模型的多个哈希的数组对象进行排序,我需要对一个在另一个模型上具有不同名称的字段进行排序
数组对象跟随
[#<TechpackAttachment id: 16, company_id: 1, version_id: 38, techpack_identifier: "5bb55062-db53-11e3-abae-d43d7e129fac", body: nil, attachment_description: nil, document_file_name: "sandle.jpg", document_content_type: "image/jpeg", document_file_size: 5717, document_updated_at: "2014-05-22 10:15:36", creator_id: 1, updater_id: 1, created_at: "2014-05-22 10:15:36", updated_at: "2014-05-22 10:15:36", is_primary_image: false>, #<SampleImage id: 13, company_id: 1, vendor_id: 1, sample_id: 4, body: nil, attachment_description: nil, private_to_vendor: 0, image_file_name: "53.png", image_content_type: "image/png", image_file_size: 318585, image_updated_at: "2014-02-19 13:24:05", creator_id: 1, updater_id: 1, created_at: "2014-02-19 13:24:05", updated_at: "2014-02-19 13:24:05", is_primary_image: false> ]
在上面的对象中,我需要按在 SampleImage 模型中具有不同名称的 document_file_name 排序,它是 image_file_name。
我做的是
@rec = @rec.sort_by {|i| i.document_file_name.nil? ? i.image_file_name : i.document_file_name }
给我错误
undefined method `document_file_name' for #<SampleImage:0xa9cb9298>
编辑
例如,我只放了两个模型,但数组对象中有 10 个模型,其中一些在其哈希中包含文档,而另一些则包含图像。
【问题讨论】:
-
是的,我知道,但数组是两个模型的组合。
标签: ruby-on-rails arrays sorting activerecord hash