0

I am creating a rails app where I have implemented the following search function.

application.html.erb

<div class="searchbar">
  <%= form_tag(articles_path, :method => "get", id: "search-form") do %>
    <%= text_field_tag :search, params[:search], placeholder: "    Search", :class => "search_form"  %>
    <%= submit_tag "Search", :name => nil %>
  <% end %>
</div>

article.rb

def self.search(search)
    where("title LIKE ? OR creator LIKE ? OR description LIKE ?", "%#{search}%", "%#{search}%", "%#{search}%") 
end

articles_controller.rb

def index
    @articles = Article.all
    if params[:search]
        @articles = Article.search(params[:search]).order("created_at DESC")
    else
        @articles = Article.all.order("created_at DESC")
    end
end

This allows me to search for all primary resources but does not include nested resources in the search results. Is there a way to include these resources within the same function?

dsteinbr1
  • 77
  • 11
  • 1
    Nested how? It depends completely on what the assocation is. – max Oct 12 '18 at 03:11
  • A bit of refactoring: code in your ```self.search(search)``` can be replaced with ```where("title LIKE :search OR creator LIKE :search OR description LIKE :search", { search: "%#{search}%" })``` – Ilya Konyukhov Oct 12 '18 at 03:16

1 Answers1

0

You'd need to do some joins, and define a syntax for passing the relevant join info into your search method.

This can get complicated pretty quick, and I'd highly suggest you don't reinvent the wheel and use an existing solution such as ransack. This will let you do things like

Article.ransack(title_cont: "code", author_name_cont: "bob").result

where, in this example, Author is its own model, associated with Article, and containing the field name.

It also plays very nice with views and forms, so you can very easily implement search forms without having the manually key everything up to the right association and field.

(Personally I'm not in love with their concatenation syntax but it gets the job done.)

Andrew Schwartz
  • 4,440
  • 3
  • 25
  • 58
  • I've looked into Ransack but it doesn't seem to work for my project as the search function is at the top of every page as opposed to just the index. Are you aware of any ways around this? – dsteinbr1 Oct 13 '18 at 18:40
  • Not sure what you mean, you can use ransack search methods in any part of your code or any controller, and you can place ransack forms in any view. Just put the code where you want it. Is this not something that is working out? – Andrew Schwartz Oct 14 '18 at 13:34
  • Because I am using the search form in the header for the entire app, when I leave the index page to view a record i get the following error... No Ransack::Search object was provided to search_form_for! I was able to work around this error using the answer suggester here: https://stackoverflow.com/questions/21351680/no-ransacksearch-object-was-provided-to-search-form-for – dsteinbr1 Oct 25 '18 at 00:46