mr_muscle
mr_muscle

Reputation: 2900

Rails show record start from db with specific letters

I want to show only those inquiry processes where company name starts from specific letters. I thought I should use start_with? but in the code below I've an error

NoMethodError (undefined method `start_with?'

def call
  InquiryProcess.all.includes(inquiry_field_responses: :inquiry_field).select do |process|
    process.inquiry_field_responses.select do |inquiry_field_responses|
      inquiry_field_responses.inquiry_field.name == 'company_name'
    end&.last&.value == start_with?('aaa')
  end
end

Upvotes: 0

Views: 60

Answers (2)

3limin4t0r
3limin4t0r

Reputation: 21130

I would do something like this:

field = InquiryField.find_by!(name: 'company_name')
response_table = InquiryFieldResponse.arel_table
responses = field.inquiry_field_responses.where(response_table[:value].matches('aaa%'))
processes = InquiryProcess.where(id: responses.select(:inquiry_process_id))

First select the field that you want to check the values of. From there select all responses that belong to that specific field and start with 'aaa'. Then select the processes using the responses.


The issue with your current code is that you'll do:

'some string' == start_with?('aaa')

Which should be:

'some string'.start_with?('aaa')

Or more specific to your case:

end.last&.value&.start_with?('aaa')

Upvotes: 3

mechnicov
mechnicov

Reputation: 15288

It's much more easier.

Just use SQL for this:

InquiryProcess.where("company_name LIKE ?",  "aaa%")

This shows you all inquiry_processes that company_name starts with aaa

Upvotes: 2

Related Questions