【问题标题】:rails 2 and ruby 1.9.2 sort_by on array of multiple hashes of different modelrails 2 和 ruby​​ 1.9.2 sort_by 在不同模型的多个哈希数组上
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我认为这会有所帮助。

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

    【讨论】:

    • 我不明白你的答案(没有代码的部分)。
    • 我只是将对象与类名分开。
    • 我知道。我理解这部分。我不明白的是“我这是有帮助的”。句子。
    • 现在好多了。虽然我认为它应该更具描述性。
    猜你喜欢
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    相关资源
    最近更新 更多