使用ruby数组每个显示成单个textarea?

时间:2015-01-20 10:34:15

标签: ruby ruby-on-rails-3

我的红宝石中有一个数组,如下所示:

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

查看:

所以我可以在textarea中显示详细列表,如下所示:

<%= 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)在返回第一个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

3 个答案:

答案 0 :(得分:1)

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

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'

答案 1 :(得分:1)

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

顺便说一下,提供数据不是您的模范责任。应该在视图部分或演示者中完成。

答案 2 :(得分:0)

我认为您应该使用mapcollect代替each