Rails选择并连接列的子集

时间:2015-06-10 13:46:55

标签: ruby-on-rails

我有以下ActiveRecord行:

#<Location id: 1, name: "TEST center", description: nil, address: "Some road along the way", city: "Porto", country: "PT", latitude: nil, longitude: nil, created_at: "2015-06-05 19:03:04", updated_at: "2015-06-05 19:03:04">

我需要得到的是:

Some road along the way,Porto,PT

这是addresscitycountry的昏迷分隔列表。

我试图先调用select并将其转换为哈希值,但无济于事,有什么想法?

2 个答案:

答案 0 :(得分:1)

有几种解决方案有很多变化。这是两个:

1。您可以将它们放在一个数组中然后加入它:

[location.address, location.city, location.country].join(',')

2。你也可以使用字符串插值:

"#{location.address},#{location.city},#{location.country}"

您可以将它们包装在模型中的方法中,也可以创建Rails帮助程序。

在模型中:

class Location < ActiveRecord::Base

  # Your other code here

  def description
    [address, city, country].join(',')
  end
end

帮助方法:

def location_description(location)
  [location.address, location.city, location.country].join(',')
end

答案 1 :(得分:0)

Location模型中创建方法

def full_address
  address+", "+city+","+country
end

@location = Location.find(id)
@location.full_address