简体   繁体   中英

Rails Searching Across Multiple Models

I have a Project model which has many UserStories. What I want is to let users search at their profile in their Projects by title , description or UserStory#name . I succeeded in searching by title and descripion . Any help on how to make the searching by UserStory#name work?

This is my form in views/profile/index :

<%= form_tag "profile/", :method => :get do %>
  <%= text_field_tag :search %>
  <%= submit_tag "Search"%>
<% end %>

And here is my index action in profile/controller:

def index   
  if params[:search]    
    @projects = current_user.projects
                  .where( 'title LIKE ? or description LIKE ?',
                          "%#{params[:search]}%", "%#{params[:search]}%" )

    current_user.projects.each do |project|
      if (project.user_stories)
        project.user_stories.each do |story|
          if story.name.include? params[:search]
            @projects << story.project
          end
        end
      end
    end

    @projects = @projects.page(params[:page]).per_page(4)
  else
    @projects = current_user.projects.order("title")
                  .page(params[:page]).per_page(4)
  end       
end

infused has it right; you can do this in one query. You can also do a lot to simplify your code.

def index
  if params[:search]
    values = { search: "%#{ params[:search] }%" }

    conditions = %q{ projects.title          LIKE :search
                     OR projects.description LIKE :search
                     OR user_stories.name    LIKE :search }

    @projects = current_user.projects.joins(:user_stories)
                  .where(conditions, values)
  else
    @projects = current_user.projects.order(:title)
  end      

  @projects = @projects.page(params[:page]).per_page(4) 
end

You can include the other table in the query and then add conditions in the where clause:

s = "%#{params[:search]}%"
current_user.projects.includes(:user_stories).where('title LIKE ? OR description LIKE ? OR user_stories.name LIKE ?', s, s, s)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM