0

I don't really like how it looks method all especially that part .group_by{|x| x.week_number}.values as this part can be replaced? week_number is the instance method in UserUpdate model.

user_updates_controller.rb

def all
  @weekly_updates = current_user.user_updates.group_by{|x| x.week_number}.values
end

user_update.rb

def week_number
  (((created_at.utc) - user.first_program_started_at.utc.beginning_of_day) / 86400 / 7).ceil.to_i || 1
end
  • I'm sorry, I don't quite understand what you're asking. Can you clarify what your concern is with your present code, and what you envision you'd like to achieve? – Paul Richter Apr 03 '14 at 13:49
  • @PaulRichter the code works, but I think this code is incorrect and would like to refactor. – Artem Garbin Apr 03 '14 at 13:57
  • @PaulRichter so for example: group_by(:week_number). But I have an error, there is no field `week_number` in the database. How can I then call the instance method `week_nubmer` from model? – Artem Garbin Apr 03 '14 at 14:00

1 Answers1

0

Alright, I believe I understand better now, but let me know if this is still not quite what you want.

I believe in your case, you can simply do this:

  @weekly_updates = current_user.user_updates.group_by(&:week_number).values

The &:week_number notation is a shorthand for creating a proc, and will effectively invoke the week_number method on the object passed in (in this case a UserUpdate object). Ultimately, you should see exactly the same result. There wouldn't be any performance difference, so its mainly just pretty-fying your code.

Check out this question and the answers for lots of examples and explanations on that &: notation.

Community
  • 1
  • 1
Paul Richter
  • 10,908
  • 10
  • 52
  • 85
  • ok, how to use sql `group by`, not the array? if it is possible? – Artem Garbin Apr 03 '14 at 14:37
  • @user3458697 Unfortunately, you won't be able to use your `week_number` method in SQL. You'll either have to re-write your method in SQL, or *maybe* use a library like [arel](https://github.com/rails/arel) or [squeel](https://github.com/activerecord-hackery/squeel) (not certain as I've never used either of those). Alternatively, most RDBMSes have date functions, such as `week()` in MySql, so re-writing in sql might be as simple as using the correct date function. However, `group` and `group_by` will give different results. – Paul Richter Apr 03 '14 at 15:50