0

I need to make a query from a Student table. But in the students table it has only one date column(joining_date). I need to get all the students who has joined from beginning of that month to end of that month... I am getting as params @start_date = "2013-09-01"

I tried like the below.. But didn't work.

Student.find(:all, :conditions => ["joining_date=? and joined=?",@start_date.beginning_of_month..@start_date.end_of_month,true])

So is there any way to do this.. Or is it better to query via named_scope.

4

2 回答 2

2
named_scope :joined,   lambda { { :conditions => { :joined => true } } }
named_scope :in_month, lambda { |date| { :conditions => ["? <= joining_date AND joining_date <= ?",
                                                          date.beginning_of_month, date.end_of_month]} }

Student.joined.in_month(@start_date)
于 2013-09-10T21:08:41.227 回答
0
Student.where(joined: true, 
  joined_date: @start_date.beginning_of_mont..@start_date.end_of_month)

您可以接受哈希条件中的范围!但不是在 SQL 字符串条件下......

如果要使用占位符的字符串条件:

Student.where(':start_of_month <= joined_date AND joined_date <= :end_of_month',
                start_of_month: @start_date.beginning_of_month, 
                end_of_month: @start_date.end_of_month)
       .where(joined: true)

顺便问一下,这个join属性有用吗?我的意思是如果加入日期存在,学生是join真的,不是吗?

无论如何,最好的方法是将那些脏查询移动到一个范围内:

scope :joined, -> { where(join: true) }

scope :during_month, -> month { where(joined_date: month.beginning_of_month..month.end_of_month) }

然后,你可以写Student.joined.during_month

我只是注意到这是为 Rails 2抱歉

于 2013-09-10T21:43:11.140 回答