How to write search scope where

Asked 2 years ago, Updated 2 years ago, 36 views

I am currently creating a search form on scope.I want to search for multiple columns from two models and one model, but I don't know what it says.Currently, I can search for one column for each of the two models, but I'm worried because I don't know more than one column. I'll list the corresponding parts below.

order.rb

scope:search_by_keyword, ->(keyword){
      where("orders.name LIKE:keyword", keyword:"%#{sanitizize_sql_like(keyword)}%") if keyword.present?
   }

I'd like to have multiple columns in the scope here, but the above is a description that works fine, and I thought I should add or to the keyword: but I got an error.

Error Order.rb Description

scope:search_by_keyword, ->(keyword){
      where("orders.name LIKE orders.address LIKE:keyword", keyword: "%#{sanitize_sql_like(keyword)}%", keyword: "%#{sanitize_sql_like(keyword)}%") if keyword.present?
   }

Error Contents

SQLite3::SQLException:near"or":syntax error:SELECT COUNT(*) FROM "orders" INNER JOIN" users"ON" users".id"="orders".user_id" WHERE(users.name LIKE'%take%)OR(orders.name LIKE or address'%LIKE')

Just for your information, this is the description of orders_controller.rb

def index
  if params [:q]
    relationship=Order.joins(:user)
    @orders=relationship.merge(User.search_by_keyword(params[:q]))
                    .or(relationship.search_by_keyword(params[:q]))
                    .paginate(page:params[:page])
  else
    @orders=Order.paginate(:page=>params[:page],:per_page=>10)
  end
end

Also, just in case, views/orders/index

<div>
  <%=form_tag(orders_path, method::get)do%>
    <div>
      <%=search_field_tag "q", params[:q], placeholder: "keyword search" %>
      <span>
        <%=submit_tag "Search"%>
      </span>
    </div>
  <%end%>
</div>

That's all.It may be written in scope, but I don't understand more than one case at all, so if you understand, please take care of me m(._.)m

ruby-on-rails ruby

2022-09-30 17:41

1 Answers

Self-resolved.

Affected parts

scope:search_by_keyword, ->(keyword){
  where("(orders.name LIKE:keyword)OR(orders.address LIKE:keyword), keyword:"%#{sanitizes_sql_like(keyword)}%") if keyword.present?
}

( ) and ( ) : It seemed like the answer was to put the keyword in ( ).As I wrote at the time of the error, I'm glad I didn't repeat the second half.


2022-09-30 17:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.