2013-07-23 2 views
0

나는 하나의 변수에 데이터베이스에서 여러 값을 검색하고 모든 것을 반환하려고합니다. 여기에 내가레일 데이터베이스에서 여러 값을 얻을

my_hash = { 
    'name' => 'John' 
    'current_location' => 'Sweden' 
} 

이 지금은 데이터베이스에 가서 모든 레코드를 검색하고 하나의 변수로 저장해야하고 있는가, 그리고 내가 모든 일을 반환 할 수 있도록 my_hash에 그 변수를 추가해야 할 것입니다. 내가 어떻게 그럴 수 있니?

예 :

last_names = Names.where('first_name = ?', 'John').select('last_name').last_name 
my_hash.add(last_names) 
return my_hash 

는 이제 위의 작품은, 누군가가 나에게 이것을 달성하기위한 적절한 방법을 알 수없는?

답변

1

다음을 시도 하시겠습니까?

# get name objects from the database 
# add select as an optimization if desired 
last_name_list = Names.where('first_name = ?', 'John') 
# get an array of only the last_name fields 
last_names = last_name_list.map { |name| name.last_name } 
# assign the array to the new hash key 'last_names' 
my_hash['last_names'] = last_names 

그지도에 유의지도 문서에 대한 http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-map을보고 수집 업데이트

my_hash = { 
    'name' => 'John' 
    'current_location' => 'Sweden' 
} 

my_hash['last_names'] = Names.where('first_name = ?', 'John') 
    .select('last_name') 
    .map { |name| name.last_name } 
# or shorthand version .map(&:last_name) 

return my_hash 

그렇게 용서 같은

names = Names.where('updated_at >= ?', Date.parse('2013-01-01')) 

# get an array of 'full names' 
full_names = names.map do |name| 
    "#{name.first_name} #{name.last_name}" 
end 
+0

내가 루비에 새로운 오전 또 다른 예이다 하지만 당신이 가지고있는 코드의 마지막 줄을 이해하지 못합니다 : .map. 나는 그것이 무엇을하는지 전혀 모른다. 아마도 select 문이 최소 3 개의 값을 반환한다고 추가해야합니다. – Bojan

+1

이 더 많은 예제로 업데이트되었으므로 명확하게 설명 할 수 있습니까? 'map'은 기존 배열의 요소를 반복하여 배열을 반환합니다 (이 경우 db로부터 얻음) – house9

+0

감사합니다. 제게 많은 도움을주었습니다. 특히 속기 버전이 좋습니다. 그래도 한 가지 더 대답 해 주실 수 있습니까? 위의 예제에서 last_name 배열의 단일 단락에있는 모든 값을 나열하는 방법은 무엇입니까? my_hash [ 'last_names'] [0]의 행을 따라 뭔가를 수행할까요? – Bojan

관련 문제