rails 2和ruby 1.9.2 sort_by在不同模型的多个哈希的数组上

时间:2014-06-11 10:19:01

标签: ruby-on-rails arrays sorting activerecord hash

我正在对数组对象进行排序,该对象具有来自两个不同模型的多个哈希值,我需要使用其他模型上具有不同名称的一个名称进行排序

数组对象正在关注

 [#<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>  ] 

在上面的对象中,我需要按document_file_name排序,它在SampleImage模型中具有不同的名称,它是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个模型,其中一些是文档,另一些是哈希的图像。

2 个答案:

答案 0 :(得分:2)

您可以检测对象是否响应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

答案 1 :(得分:0)

我认为这会有所帮助。

@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 }