[英]rails 2 and ruby 1.9.2 sort_by on array of multiple hashes of different model
我正在对来自两个不同模型的具有多个哈希的数组对象进行排序,我需要对另一个模型具有不同名称的字段进行排序
数组对象跟随
[#<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个模型,其中一些模型的哈希值中包含文档,其他模型中的图像中包含图像。
您可以检测对象是否响应document_file_name
方法:
@rec = @rec.sort_by do |i|
if i.respond_to?(:document_file_name)
i.document_file_name
else
i.image_file_name
end
end
我认为这会有所帮助。
@rac = [#<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> ]
@rec = @rec.sort_by { |i| i.kind_of?(TechpackAttachment) ? i.document_file_name : i.image_file_name }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.