Home>
About implementation of search function

I'm implementing a search function, but I want to retrieve only the products owned by the currently logged-in user.
I think.

Product information of all users is extracted.
Corresponding source code
places.controller.rb
  def search
    @items = Item.search (params [: keyword])
  end
item.rb
  def self.search (search)
    if search! =''
      Item.where ('name LIKE (?)', "% # {Search}%")
    else else
      Item.all
    end
  end
_header.html.rb
  <% = form_with (url: search_places_path, local: true, method:: get, class: "form-inline my-2 my-lg-0 mr-5") do | form |%>
  <% = form.text_field: keyword, placeholder: "Find a product", class: "form-control mr-sm-2"%>
  <% = form.submit "search", class: "btn btn-success"%>
  <% end%>
What I tried

I tried merge etc. but it didn't work.
If i am familiar with this, please professor.

places.controller.rb
  def search
    @items = Item.search (search_params)
  end
  private
    def search_params
       params.permit (: keyword) .merge (user_id: current_user.id)
    end
items table
class CreateItems
Supplementary information (FW/tool version, etc.)

rails 6.0.0
User management function devise
Please provide more detailed information here.

  • Answer # 1

    For example, if it is assumed that there is a logged-in user, the expected behavior may be as follows. If there is no keyword, all Items associated with the logged-in user are returned.

    @items = current_user.items.search (params [: keyword])
    def self.search (search)
        where ('name LIKE (?)', "% # {Search}%") if search.present?
      end

    Pass the user ID along with the search keyword

    where ('name LIKE (?)', "% # {Search}%"). where (user_id: user_id)


    You may be able to do something.

Related articles