Getting total result count from Rails query using will_paginate - ruby-on-rails

I get a list of objects from my Rails app, and use will_paginate to page as usual, and then I have a little method used to save details of the search to the database:
per_page=10
session[:search_params] = params[:search_people]
#documents = Person.search_people(params[:search_people], params[:page], per_page)
Search.create(:user_id => (!current_user ? 0 : current_user.id),
:search_type => "Person",
:firstname => params[:search_people][:first_name],
:lastname => params[:search_people][:last_name],
:results => #documents.count )
The problem is, the number of search results (#douments.count) is always <= per_page used for will_paginate.
I understand why this is, but is there a way around it without running the query twice, once with will_paginate and once without?

Try <%=#documents.total_entries%>

Related

Ruby on Rails: Show default result before using dropdown filter with will_paginate

I can display the results by 10, 15, or 20 by using a drop-down. The issue is when the app loads it displays all results. I would like to display only 10 results by default before using the drop-down filter to display more results.
Can someone help please?
Thank you!
This is my VIEW:
<%= select_tag :per_page, options_for_select([10,15,20], #per_page), :onchange => "if(this.value){window.location='?per_page='+this.value;}" %>
This is my CONTROLLER:
#per_page = params[:per_page] || Post.per_page
#posts= Post.all.paginate(:per_page => #per_page, :page => params[:page])
Try this code:
#per_page = params[:per_page] || Post.per_page
#posts= Post.paginate(per_page: #per_page, page: params[:page])
Note that I call paginate without on Post class itself and not on result of Post.all.
I also removed the last || 10 part. I think you don't need it there as you already set this value on Post model.

Paginating a solr response using kaminari?

Does kaminari support pagination of a solr response ? If yes, how to convert the response to a kaminari-compatible format ?
Set up Kaminari for your project as described here - http://railscasts.com/episodes/254-pagination-with-kaminari
In your controller, if you have the following to perform the Solr search -
#vehicles = Vehicles.search do
with (:year => 2012)
paginate :page => params[:page], :per_page => 20
end
You need to add the following in your view to get the pagination links -
<%= paginate #vehicles.hits %>
Hope that helps!

Can't sort table in rails

I'm having trouble sorting a single-column table in Rails. Each row represents a single object (an article) and contains all of its attributes (name, content, created_at, user, etc.). The search function works fine (Article.where) but I can't seem to sort the table by any attributes, i.e. Article.order('attribute'). The default, which I can't change, is created_at desc. Am I overlooking something?
Here is my controller:
def index
#title="Home"
if params[:search]
#search=params[:search]
#articles=Article.where('name LIKE ? OR category LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%").paginate(:per_page => 15, :page => params[:page])
else
#articles=Article.order('name').paginate(:per_page => 15, :page => params[:page])
end
end
And view:
<table>
<%= render #articles%>
</table>
<%= will_paginate #articles, :previous_label => "Prev", :next_label => "Next" %>
Use reorder to override any default ordering.
Article.reorder('name').paginate(:per_page => 15, :page => params[:page])
I recommend my gem simple-search for these problems. It may be too simple, but worth a shot.

Rails & Sunspot facets and filtering

Pretty much a noobie here, so I appreciate any help someone can give.
I'm trying to add faceting to the search on my site through Sunspot. Ryan just released a great Railscast which got me started: http://railscasts.com/episodes/278-search-with-sunspot. I got that working and was able to add additional facets. My problem is that the facets are independent of each other. If I have 3 facets on 3 different attributes, when I select a facet once I already have on selected, I would like to display only results falling into both of those facests. As of now, it just switches from one facet to the other. I feel like this shouldn't be that difficult, but I can't figure out how to do it.
I did find this tutorial: http://blog.upubly.com/2011/01/06/using-sunspot-in-your-views/ which I think is doing what I want. I tried to get this working but, even when I attempt to make it work with just one facet I don't any results listed. Just the facet name and then nothing else.
Thoughts?
Thank you!!
UPDATE
Here is the code samples of what I am trying to do:
Adjusting the Railscasts code I got this:
In my StylesController:
def index
#search = Style.search do
fulltext params[:search]
facet :departmental, :seasonal, :classifier
with(:departmental, params[:department]) if params[:department].present?
with(:classifier, params[:classification]) if params[:classification].present?
with(:seasonal, params[:season]) if params[:season].present?
end
In my Style Index view (I know I need to condense this)
= form_tag styles_path, :method => :get do
%p
= text_field_tag :search, params[:search]
= submit_tag "Search", :name => nil
#facets
%h4 Departments
%ul
- for row in #search.facet(:departmental).rows
%li
- if params[:department].blank?
= link_to row.value, :department => row.value
(#{row.count})
- else
%strong= row.value
(#{link_to "remove", :department => nil})
%h4 Classifications
%ul
- for row in #search.facet(:classifier).rows
%li
- if params[:classification].blank?
= link_to row.value, :classification => row.value
(#{row.count})
- else
%strong= row.value
(#{link_to "remove", :classification => nil})
%h4 Seasons
%ul
- for row in #search.facet(:seasonal).rows
%li
- if params[:season].blank?
= link_to row.value, :season => row.value
(#{row.count})
- else
%strong= row.value
(#{link_to "remove", :season => nil})
In my Style Model:
searchable do
text :number, :description, :department, :classification, :season
string :departmental
string :classifier
string :seasonal
end
def departmental
self.department
end
def classifier
self.classification
end
def seasonal
self.season
end
And my version of the upubly code, paired down to just try to get the "seasonal" facet working:
I left the the Search Partial, the Search Model and the SearchHelper the same as in the example. I tried to mess with the Helper as my Facets will be pulling text values, not just IDs of other Models, but to no avail. I don't have my various attributes set up as individual Models as I didn't think I needed that functionality, but I am starting to think otherwise.
StylesController:
def index
#title = "All styles"
#search = search = Search.new(params[:search]) # need to set local variable to pass into search method
#search.url = styles_path
#search.facets = [:seasonal]
#solr_search = Style.search do
keywords search.query
with(:seasonal, true)
search.facets.each do |item|
facet(item)
with(:seasonal, params[:season]) if params[:season].present?
end
any_of do
# filter by facets
search.facets.each do |item|
with(item).all_of( params[item].try(:split, "-") ) if params[item].present?
end
end
paginate(:page => params[:page], :per_page => 10)
end
Again, I appreciate the help. Definitely a noob, but really enjoying the process of building this site. Stackoverflow has been a HUGE help for me already, so I owe everybody who posts answers on here a big-time thank you.
I needed the answer to this myself, and seeing as there seems to be nothing else on the web about it, I decided I'd try to figure it out myself.
First I came to the conclusion through logic, that the controller can handle multiple facets and there's no reasons it cannot, I remembered that the best part about ruby is that it is the most human readable code, try to read your first controller and you'll see that it makes sense that it works. I tested this by manually entering in a query string in url, which returned expected results. Therefore, once I figured that out, I knew the issue resided in my view (which made me facepalm because it's fairly obvious now)
Your example is significantly more complex than mine, and my answer might not 100% meet every requirement but I'm pretty sure it's close. Also your code in your model regarding "departmental" etc is a little redundant in my view
Controller
def index
#search = Style.search do
fulltext params[:search]
facet :departmental, :seasonal, :classifier
with(:departmental, params[:department]) if params[:department].present?
with(:classifier, params[:classification]) if params[:classification].present?
with(:seasonal, params[:season]) if params[:season].present?
end
View
%h4 Departments
%ul
- for row in #search.facet(:departmental).rows
%li
- if params[:department].blank?
= link_to row.value, styles_path(
:department => row.value,
:classification => (params[:classification] unless params[:season].blank?),
:season => (params[:season] unless params[:season].blank?))
(#{row.count})
- else
%strong= row.value
= link_to "remove", styles_path(
:department => nil,
:classification => (params[:classification] unless params[:season].blank?),
:season => (params[:season] unless params[:season].blank?))

Searching in Ruby on Rails - How do I search on each word entered and not the exact string?

I have built a blog application w/ ruby on rails and I am trying to implement a search feature. The blog application allows for users to tag posts. The tags are created in their own table and belong_to :post. When a tag is created, so is a record in the tag table where the name of the tag is tag_name and associated by post_id. Tags are strings.
I am trying to allow a user to search for any word tag_name in any order. Here is what I mean. Lets say a particular post has a tag that is 'ruby code controller'. In my current search feature, that tag will be found if the user searches for 'ruby', 'ruby code', or 'ruby code controller'. It will not be found if the user types in 'ruby controller'.
Essentially what I am saying is that I would like each word entered in the search to be searched for, not necessarily the 'string' that is entered into the search.
I have been experimenting with providing multiple textfields to allow the user to type in multiple words, and also have been playing around with the code below, but can't seem to accomplish the above. I am new to ruby and rails so sorry if this is an obvious question and prior to installing a gem or plugin I thought I would check to see if there was a simple fix. Here is my code:
View: /views/tags/index.html.erb
<% form_tag tags_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search], :class => "textfield-search" %>
<%= submit_tag "Search", :name => nil, :class => "search-button" %>
</p>
<% end %>
TagsController
def index
#tags = Tag.search(params[:search]).paginate :page => params[:page], :per_page => 5
#tagsearch = Tag.search(params[:search])
#tag_counts = Tag.count(:group => :tag_name,
:order => 'count_all DESC', :limit => 100)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #tags }
end
end
Tag Model
class Tag < ActiveRecord::Base
belongs_to :post
validates_length_of :tag_name, :maximum=>42
validates_presence_of :tag_name
def self.search(search)
if search
find(:all, :order => "created_at DESC", :conditions => ['tag_name LIKE ?', "%#{search}%"])
else
find(:all, :order => "created_at DESC")
end
end
end
If I read your problem correctly, you want to return a row if the tag names for the row matches one of the words passed in the query string.
You can rewrite your search method as follows:
def self.search(search)
all :conditions => (search ? { :tag_name => search.split} : [])
end
If you need partial matching then do the following:
def self.search(str)
return [] if str.blank?
cond_text = str.split.map{|w| "tag_name LIKE ? "}.join(" OR ")
cond_values = str.split.map{|w| "%#{w}%"}
all(:conditions => (str ? [cond_text, *cond_values] : []))
end
Edit 1
If you want pass multiple search strings then:
def self.search(*args)
return [] if args.blank?
cond_text, cond_values = [], []
args.each do |str|
next if str.blank?
cond_text << "( %s )" % str.split.map{|w| "tag_name LIKE ? "}.join(" OR ")
cond_values.concat(str.split.map{|w| "%#{w}%"})
end
all :conditions => [cond_text.join(" AND "), *cond_values]
end
Now you can make calls such as:
Tag.search("Ruby On Rails")
Tag.search("Ruby On Rails", "Houston")
Tag.search("Ruby On Rails", "Houston", "TX")
Tag.search("Ruby On Rails", "Houston", "TX", "Blah")
Tag.search("Ruby On Rails", "Houston", "TX", "Blah", ....) # n parameters
Caveat:
The wild card LIKE searches are not very efficient(as they don't use the index). You should consider using Sphinx (via ThinkingSphinx) OR Solr(via SunSpot) if you have lot of data.
You can try to set up ferret, or if you are really bend on just using rails, try this:
# Break the search string into words
words = params[:search].blank? ? [] : params[:search].split(' ')
conditions = [[]] # Why this way? You'll know soon
words.each do |word|
conditions[0] << ["tag_name LIKE ?"]
conditions << "%#{word}%"
end
conditions[0] = conditions.first.join(" OR ") # Converts condition string to include " OR " easily ;-)
# Proceed to find using `:conditions => conditions` in your find
hope this helps =)
Sounds like you need a full text search. The best search integration right now is with Sphinx and the Thinking_Sphinx plugin. I have used it on several projects and it's super easy to setup.
You do need to install sphinx on your host so if you are using a shared host that could present some issues.
You could also use full text search in a MyISAM MySQL database, but performance on that is pretty poor.
Once you have your sphinx installed you just put what you want to index in your model and call model.search. The results will be a list of model objects. It supports will_paginate as well.
I'd suggest looking at Searchlogic if you don't want to use a separate fulltext search engine (Ferret, Sphinx, etc). It makes simple searches extremely easy, although you may not want to use it in a public facing area without lots of testing.
Also check out the Railscast on it: http://railscasts.com/episodes/176-searchlogic
1.You can do some coding in your controller post as such:-
<pre>
def show
#post = Post.find(params[:id])
#tag_counts = Tag.count(:group => :name, :order => 'updated_at DESC', :limit => 10)
respond_to do |format|
format.html # show.html.erb
format.json { render json: #post }
end
end
</pre>
2.Now make some changes in your view file:-
<pre>
<b>Tags:</b>
<%= join_tags(#post) %>
<%unless #tag_counts.nil?%>
<% #tag_counts.each do |tag_name, tag_count| %>
<tr><td><%= link_to(tag_name, posts_path(:name => tag_name)) %></td>
<td>(<%=tag_count%>)</td>
</tr><% end %>
<%end%>
</pre>
3. And one important thing is that there should be many to many relationship between tags and post.

Resources