2015-06-04 51 views
0

我有一个列名称的场合和日期的holiday_list表。根据当年显示的假期名单。如何在Ruby中从数据库中获取数组的所有日期?

class HolidayListsController < ApplicationController 
def index 
    @holidays = HolidayList.by_year(Time.now.year) 
end 
end 

模型方法的查询是这样的: -

def self.by_year(year) 
    where('extract(year from date) = ?', year) 
end 

从上面的代码中,我得到整个数据阵列中的结果

<ActiveRecord::Relation [#<HolidayList id: 1, name: "independence day", date: "2015-08-15",created_at: "2015-06-04 07:19:02", 
    updated_at: "2015-06-04 07:19:02">, #<HolidayList id: 2, name: "Republic day",date: "2015-01-26", created_at: "2015-06-04 08:39:57", 
    updated_at: "2015-06-04 08:39:57"> 

但我想作为一个日期列的所有值array.so,我可以应用这个数组在我的jQuery。

+2

回报'@ holidays.collect(:日期)' – usmanali

+1

你可以试试这个'@holidays = HolidayList.by_year(Time.now.year).collect {| d | d.date}' –

+0

thanx它的工作原理:) – Aniee

回答

1
def self.by_year(year) 
    where('extract(year from date) = ?', year) 
end 

这将使查询哪里yeareq to,那么你必须要阵列FO日期,使用pluck功能,how pluck works

def self.by_year(year) 
    where('extract(year from date) = ?', year).pluck :date 
end 

方法by_year将返回日期

array
0

HolidayList型号等级:

scope :from_year, ->(year) { time = Time.new(year); where(created_at: time.beginning_of_year..time.end_of_year) } 

然后在控制器:

def index 
    @holidays = HolidayList.from_year(Time.now.year).pluck(:date) # you can now use this for another year as well, just pass the year at the place of Time.now.year. For example: '2015' 
end 
相关问题