Need correct wording for scope method seeking specific wording in the object

42 Views Asked by At

I cannot figure the correct wording for this scope method. The task is to create a scope method that specifies the requests(which have notes) to display only the requests with the word "kids" in the note . I can't seem to get the right wording for this to work

I have tried scope :requests_with_kids_in_note, -> { where('note').includes(text: "kids")}

scope :requests_with_kids_in_note, -> { select('note').where('note').includes(text: "kids")}

error messages aren't helping

2

There are 2 best solutions below

2
bo-oz On BEST ANSWER

You can do this very easily through scopes, but you should format the where clause differently. Also I'd advise to make it more generic:

scope :note_contains, -> (word) { where('note LIKE %?%', word) }

And use it like this:

Model.note_contains('kids')
2
Daniel Batalla On

You can use Arel to compose that query.

Assuming that you have a Request that have a has_many :notes association, you can write the scope like this:

class Request < ApplicationRecord
  has_many :notes

  scope :with_kids_in_note, -> {
    joins(:notes).where(Note.arel_table[:content].matches('%kids%'))
  }
end

class Note < ApplicationRecord
  # In this model, i'm assuming that "content" is the column
  # in which you have to find the word "kids".
  belongs_to :request
end