How can I get entries around a specific entry in Ruby on Rails?

I have a model called note. I am currently receiving notes like this:

current_user.notes.order('date DESC, created_at DESC').limit(10).reverse!

Now I need to do the following: Take the note_id parameter and return 10 notes: one of the parameter and 9 others "around" the first.

Ideally, 9 other notes will be highlighted as 5 before the main recording and 4 after (or 4 before and after 5 after) based on the order in the first line above.

Example:

note note note note primary_note note note note note note

Sometimes this is not possible. For example, if primary_note is the second user entry, it should return this:

note primary_note note note note note note note note note

Or, if the last note, and the user has only 3 notes, he should return:

note note primary_note

How can i do this? I am using ruby ​​1.9.2 and Rails 3.0.1

+3
source share
2

, - . ( ) SQL, , :

  • 4 , "" primary_note
  • 4 "" primary_note

(: )

class Note < ActiveRecord::Base
  # on rails 3 I prefer class methods to named scopes.
  # they are equally "chainable" and have simpler syntax
  def self.notes_before(date, limit=4)
    self.where(['date >= ?', date]).order("date DESC, created_at DESC").limit(limit)
  end

  def self.notes_after(date, limit=4)
    self.where(['date <= ?', date]).order("created_at ASC, date ASC").limit(limit)
  end

  # Instance method
  def notes_around(limit=4)
    (Note.notes_before(self.date, limit) << self) + Note.notes_after(self.date, limit)
  end
end

:

n = Note.new(:date => Date.yesterday)
n.notes_around # returns the 9 notes around n, plus n
n.notes_around(40) # returns 81 notes

# in addition:
Note.notes_before(Date.today, 40) # last 40 notes
Note.notes_after(Date.today, 10).where(:color => 'blue') # chainable

" ". , SQL.

9 5 4 ( 4 5 )

, , "4" "5" . , .

+4

class Note
  scope :around_note_id, lambda { |id| where(:id => range_for_search(id) }

  def self.range_for_search(id)
    # your logic here, i.e.
    # (id-1)..(id+1)
  end
end

> Note.around_note_id(3)
+2

Source: https://habr.com/ru/post/1794739/


All Articles