使用 ruby 数组每个显示到单个文本区域?

Using ruby array each display into single textarea?

我的 ruby 中有一个数组,如下所示:

[#<Order::List code: 1511, Reference: "FRIA004", valuation: nil, full_Address: "1, abc road, xyz", reason_available: "Y", list: "1 : Meter cupboard generic throughout - Very low">,
 #<Order::List code: 1512, Reference: "FRIA005", valuation: nil, full_Address: "2, abc road, xyz", reason_available: "Y", list: "2 : Meter cupboard generic throughout - Very high, 3 : Meter cupboard generic throughout - Very low">,
 #<Order::List code: 1513, Reference: "FRIA006", valuation: nil, full_Address: "3, abc road, xyz", reason_available: "Y", list: "15 : Meter cupboard generic throughout - Low">,
 #<Order::List code: 1514, Reference: "FRIA007", valuation: nil, full_Address: "6, abc road, xyz", reason_available: "Y", list: "16 : Meter cupboard generic throughout - High">]

型号:

class Order::List < ActiveRecord::Base
  self.primary_key = :Code

  def self.display_details(codes)
    codes.each { |x|
      details = Order::List.where(Code: x).first
      reference = details.Reference
      address = details.full_Address
      list = details.list

      display_details = reference + "\n" + address + "\n" + list
      return display_details
  end
end

查看:

所以我可以将详细信息列表显示到文本区域中,如下所示:

<%= f.text_area :detail_list, rows: 8, value: (Order::List.display_details(codes)) %>

输出:

FRIA004
1, abc road, xyz
2 : Meter cupboard generic throughout - Very high, 3 : Meter cupboard generic throughout - Very low

问题:

1) 在return第一个code之后已经停止了。我正在使用 each 并希望将每个 code 显示到 text_area

2) 如何在逗号后的新行中显示列表(列表是这里的列)?

所以我的预期输出是

FRIA004
1, abc road, xyz
1 : Meter cupboard generic throughout - Very low

FRIA005
2, abc road, xyz
2 : Meter cupboard generic throughout - Very high
3 : Meter cupboard generic throughout - Very low

我认为你应该使用 mapcollect 而不是 each

ad 1:return 结束方法和 returns 值的处理。所以你应该这样做:

def self.display_details(codes)
  retval = ""
  codes.each do |x| 
    .......
    display_details = reference + "\n" + address + "\n" + list + '\n'
    .......
    retval << display_details
  end
  return retval
end

广告 2:只需将 \n 添加到每一行的末尾:

display_details = reference + "\n" + address + "\n" + list + '\n'
codes.map do |x|
  details   = Order::List.where(Code: x).first
  reference = details.Reference
  address   = details.full_Address
  list      = details.list

  "#{reference}\n#{address}\n#{list}\n"
end

顺便说一句,呈现数据不是您的模特责任。应该在部分视图或演示者中完成。