How to get earliest and latest dates for associated objects

不想你离开。 提交于 2019-12-10 21:12:08

问题


I am developing an Rails 4 app and I got two models. One is called Project and the other is called Task.

Project has many Tasks. Task belongs to Project.

The task objects have starts_at and ends_at attributes (datetime). How can I get the earliest starts_at and latest ends_at of all the associated tasks that belongs to a specific project?

I tried @project.tasks.max(:starts_at) but it did not work (got error).


回答1:


Use maximum instead of max.

max is for array maximum: [1,2].max == 2

http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-maximum




回答2:


Adapted from [Lars Haugseth's solution] to find next birthdays.

model.rb

def latest_tasks
  todays_date = Date.today
  start_days_from_now = todays_date - starts_at
  ends_days_from_now = ends_at - todays_date
  if start_days_from_now < ends_days_from_now
    yearmmdd = starts_at.strftime('%Y%m%d')
  else
    yearmmdd = ends_at.strftime('%Y%m%d')
  end
  return Date.parse("#{yearmmdd}")
end

Controller.rb

@project.tasks.where('starts_at >= ? or ends_at >=? ', Date.today, Date.today).sort_by(&:latest_tasks)



回答3:


I know this is an old question but for anyone looking to accomplish this, you could do it this way:

  • Get an array of all the starts_at and ends_at values from @project.tasks:

    starts_at_values = @project.tasks.pluck(:starts_at)

    ends_at_values = @project.tasks.pluck(:ends_at)

  • Select the Task record whose starts_at value is the earliest:

    earliest_task = @project.tasks.select{|task| task.starts_at == starts_at_values.min}

  • Select the Task record whose ends_at value is the latest:

    latest_task = @project.tasks.select{|task| task.starts_at == ends_at_values.max}

If you need to only get the earliest and latest times, you could just do:

earliest_time = starts_at_values.min

latest_time = ends_at_values.max


来源:https://stackoverflow.com/questions/28091778/how-to-get-earliest-and-latest-dates-for-associated-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!