2016-02-15 36 views
0

這裏是我的入門型號方法方法,不會讓我把它變成一個哈希使用的drop_down_select

def self.months 
    a = 1 
    z = 13 
    curr_year = Time.now.year 
    start_month = 0 
    while a < z 
    month = "#{curr_year}-#{start_month +=1}-01" 
    par = Date.parse(month).strftime('%Y-%m-%d') 
    a +=1 
    end 
end 

^這個吐出這

2016-01-01 
2016-02-01 
2016-03-01 
2016-04-01 
2016-05-01 
2016-06-01 
2016-07-01 
2016-08-01 
2016-09-01 
2016-10-01 
2016-11-01 
2016-12-01 

我怎樣才能把這些數據變成一個哈希來用於下拉選擇? 我試過這個(下面),但我得到了未定義的方法`拆分'爲零:NilClas任何幫助將不勝感激。

h = {} 
    q = Entry.months 
    r = q.split(",") 
    z = r.each{|a| h[a] = 0} 
+1

self.months returns'nil' - http://ruby-doc.org/core-2.2.0/doc/syntax/control_expressions_rdoc.html#label-while+Loop – Anthony

+0

你究竟想要傳遞什麼選擇?我的意思是,當你選擇說1月1日時,你想要選擇什麼值? –

回答

1
def self.months 
    a = 1 
    z = 13 
    curr_year = Time.now.year 
    start_month = 0 
    while a < z 
    month = "#{curr_year}-#{start_month +=1}-01" 
    par = Date.parse(month).strftime('%Y-%m-%d') 
    a +=1 
    end 
end 

你不是實際的返回,你需要把它們放入數組並返回它們的日期。

def self.months 
    months = [] 
    a = 1 
    z = 13 
    curr_year = Time.now.year 
    start_month = 0 
    while a < z 
    month = "#{curr_year}-#{start_month +=1}-01" 
    months << Date.parse(month).strftime('%Y-%m-%d') 
    a +=1 
    end 
    months 
end 

但我會改變,要

def self.months 
    curr_year = Time.now.year 
    (1..12).map do |month| 
    month = "#{ curr_year }-#{ month }-01" 
    Date.parse(month).strftime('%Y-%m-%d') 
    end  
end 

而且爲你選擇你想要一個二維數組。如果這是這一切的方法是你可以做

def self.months 
    curr_year = Time.now.year 
    (1..12).map do |month| 
    month = "#{ curr_year }-#{ month }-01" 
    [Date.parse(month).strftime('%Y-%m-%d'), my_select_value] 
    end  
end 

代my_select_value你想要的值,成爲該項目的內容。

+0

@Anthony是的,只是注意到了。我不應該複製和粘貼.. –

+0

您不必創建中間日期字符串。只需使用'Date.new(curr_year,month).strftime('%F')' – Stefan

+0

甜蜜的謝謝你! @ J-dexx –

相關問題