I'm writing an application to manage clothes using rails 5.2.4.
I have implemented a search function on My Page and want to display only the search results of users who are logged in to My Page.

If the keywords match when executing the search, the posts of other users will also be displayed as search results.

Corresponding source code
# topp model
class Topp</pre>
<strong>What I tried</strong>
<p>○ Add current_user to @topp_images = Topp.search (params [: keyword])<br />
○ Add params (current_user) using marge method<br />
○ Added current_user to @topp_images in view</p>
<p>I got some kind of error and it's been stuck for about 2 days ...</p>
<strong>Supplementary information (FW/tool version, etc.)</strong>
<p>I am using gem'devise'<br />
<pre><code>= form_with (url: search_topp_path, local: true, method:: get) do | form |
= form.text_field: keyword, placeholder: "topps category", class: "searchbox" = form.submit "serach", class: "searchbtn"

Enter your search information in

of topps.contoroller

def search
@topp_images = Topp.search (params [: keyword])
@bottom_images = current_user.bottoms
user = User.find (params [: id])
@nickname = user.nickname

Received information as @topp_images


    [email protected] topp_images.each do | t_image |
      = link_to image_tag (t_image.image.to_s, class: "topps__container__image"), "/topps/#{t_image.id}", method:: get

Information is passed to @topp_iamges and the search results are displayed. At this time, if the search keywords match, the information of other users will also be displayed, which is a problem. How should I write to display only the search results of the logged-in user? I would appreciate it if you could teach me.

  • Answer # 1

    @topp_images = Topp.search (params [: keyword])To
    @topp_images = Topp.where (user_id: current_user.id) .search (params [: keyword])To

Related articles