开发者

Active Record Query Using Associated Model in Find Clause

开发者 https://www.devze.com 2023-03-23 15:40 出处:网络
I\'m having a blonde moment and probably a brain freeze. In my rails3 app, I have users and tasks. My users have many tasks...

I'm having a blonde moment and probably a brain freeze.

In my rails3 app, I have users and tasks. My users have many tasks...

I have due and overdue tasks as follows:

@due = Task.find(:all, :conditions => ["dueddate >= ? AND AND status = ?", Date.today, false], :include => :taskcategories, :order => "dueddate asc")  

What I want to do in my tasks view, is list the users with due tasks...

For some reason, I can't get my head around it. I have tried this, but it's not working:

@task = Task.all

@user = User.find(:all, :conditions => ["@task.dueddate <= ? AND 
@task.status = ?", Date.today + 7.days, fal开发者_JAVA技巧se])

I'm sure this is easy, can anyone help me!!?


I guess this should work

updated

User.joins(:tasks)
    .where("tasks.dueddate <= ? AND tasks.status = ?", Date.today + 7.days, false).group(:id)

This should work with SQLite and MySQL. However, PostgreSQL requires that you supply all the columns of the table. If it's a small table, you could simply type the names. Or you could add this method to the model:

def self.column_list
  self.column_names.collect { |c| "#{self.to_s.pluralize.downcase}.#{c}"}.join(",")
end

and change .group(:id) to .group(User.column_list)

0

精彩评论

暂无评论...
验证码 换一张
取 消