在数组中查找值

时间:2018-08-09 11:48:27

标签: ruby-on-rails ruby

我遇到了问题,我们将不胜感激。

我有一个rails查询

array = Issue.where("tracker_id =? AND project_id = ?",8,140).first.custom_field_values

这将返回一个像这样的数组:

[#<CustomFieldValue:0x000000074d8b98 @custom_field=#<IssueCustomField id: 4, type: "IssueCustomField", name: "Phase Injected", field_format: "list", possible_values: ["Planning", "Requirements", "Design", "Coding", "Testing"], regexp: "", min_length: nil, max_length: nil, is_required: true, is_for_all: true, is_filter: true, position: 4, searchable: false, default_value: "", editable: true, visible: true, multiple: false, format_store: {"url_pattern"=>"", "edit_tag_style"=>""}, description: "", formula: nil, is_computed: false>, @customized=#<Issue id: 43, tracker_id: 8, project_id: 140, subject: "Cost of rework is  not calculated for past sprints", description: "", due_date: nil, category_id: nil, status_id: 1, assigned_to_id: 5, priority_id: 2, fixed_version_id: 1, author_id: 8, lock_version: 3, created_on: "2018-07-26 05:40:19", updated_on: "2018-08-09 10:46:12", start_date: "2018-07-26", done_ratio: 0, estimated_hours: nil, parent_id: 42, root_id: 42, lft: 2, rgt: 3, is_private: false, closed_on: nil, sprint_id: nil, position: nil>, @value="Planning", @value_was="Planning">,.....]

上面的数组有10个以上的结果粘贴到第一个结果中。

我如何在此数组内搜索名称='Phase Injected',并获得@value的结果,即'planning'。

当前,我正在尝试通过以下方式进入数组:

<% array.each do |cf| %>
  <% if cf.custom_field.name = "Phase Injected" %>
    <%= cf %> #this returns @value
  <% end %>
<% end %>

我可以不array.find_by_something来获取价值吗?

谢谢

1 个答案:

答案 0 :(得分:4)

它首先返回活动记录关系对象,而不是数组。是的,但是它像数组一样嘎嘎叫。

您应该直接在数据库中过滤数据,而不是极其无效的数组过滤:

Issue.
  joins(:issue_custom_fields).
  where(tracker_id: 8, project_id: 140).
  where('`issue_custom_fields`.`name` = "Phase Injected"')

或者,如@Stefan在评论中建议的那样:

Issue.
  joins(:issue_custom_fields).
  where(tracker_id: 8, project_id: 140).
  where(issue_custom_fields: { name: 'Phase Injected' })