I have a simple Rails app which has an index page that shows 59 posts.
The problem is that if I search for something, Post.count continue to show me the original number of Posts on the index page - for example if I search for a post called 'Quilon', I get a search result showing just 1 post, but the Post.count still shows the original post number which is 59.
How do I fix this?
INDEX.HTML.ERB CODE
<%= Post.count %>
SEARCH FUNCTION IN POSTS CONTROLLER
def index
#posts = Post.all
if params[:search]
#posts = #posts.search(params[:search]).order("created_at DESC")
end
if params[:zagat_status].present?
#posts = #posts.zagat_status(params[:zagat_status]).order("created_at DESC")
end
end
In your index action you narrow down the posts using some conditions, so you should operate on #posts variable, not on the model Post itself.
Which means you want to use #posts.count.
You should give <%= #posts.count %> instead of <%= Post.count %>. <%= Post.count %> returns count of all the records. It is just same as
select count(*) from "posts"
so the conditions are ignored.
Use #posts.count instead of Post.count
Related
I'm building a Rails app where I have individual entries called films. I would like to display the latest entry's link on the homepage (separate controller) and I'm struggling to make it work.
My films_controller.rb is as follows (excerpt):
def show
#film = Film.find(params[:id])
end
My home_controller.rb only has the following:
def index
end
And my view file (index.html.erb) has the following:
<%= link_to #film.last.filmTitle, film_path(#film) %>
I'm getting the following error:
Couldn't find Film with 'id'=#<Film::ActiveRecord_Relation:0x007fc93f2d1fd0>
With the #film.find(params[:id]) highlighted.
Thanks!
The last method:
Find the last record (or last N records if a parameter is supplied). If no order is defined it will order by primary key.
source
You can add a #last_film instance variable in your index controller and use it in the view.
def index
#films = Film.all
#last_film = Film.last
end
and in your index.html.erb
<%= link_to #last_film.filmTitle, film_path(#last_film) %>
The index method need something, currently, it didn't connect with ActiveRecord like model or table, that's why
Couldn't find Film with 'id'=#<Film::ActiveRecord_Relation:0x007fc93f2d1fd0>
So if you need to show recent posts in the index then you could something like this
def index
#films = Film.limit(10).order(created_at: :desc) #=> or you can use id
end
it will show last 10 records, for this in the index.html.erb like this
<% #films.each do |film| %>
<%= link_to film.filmTitle, film_path(film) %>
<% end %>
In the other hand if you need to show only one post which is the last then you should modify this query like this like limit(10) to limit(1) or you can use use the last method like this
def index
#film = Film.last
#or
##films = Film.limit(1).order(created_at: :desc) #=> or you can use id
end
if you use this #film = Film.last then your index file will like this
<%= link_to #film.filmTitle, film_path(#film) %>
otherwise, you need to use each method which describes before.
So I am using the tags provided by the acts_as_taggable gem. The posts are what I am tagging. How could I say something (pseduocode here) like =>
if a collection of Posts has a tag with a corresponding StockQuote, display the stock quote
So right now I have a Post resource that acts_as_taggable. Here is what my posts index action looks like now:
def index
#stock = StockQuote::Stock.quote("symbol")
if params[:tag]
#posts = Post.tagged_with(params[:tag])
else
#posts = Post.order('cached_votes_score desc')
end
end
So I would somehow have to iterate through all the #posts tagged_with params[:tag] and compare the tags to stock quotes. And display the quote on the index of all the #posts tagged_with params[:tag] if there is a match. I am going to try to figure out how to limit each post to have 1 tag soon
How could I use the :tag of a post to access a stock quote if that tag happens to be a stock quote?
I think you would want to do something like:
#symbols = #post.tag_list
#quotes = StockQuote::Stock.quote(#symbols)
Since a post could actually be tagged with multiple symbols you will want to fetch them all at once and then iterate over the result in the view. Something like:
<% #quotes.each do |quote| %>
<%= "#{quote.symbol}: #{quote.ask}" %>
<% end %>
I am not familiar with the gems all that much but with quick glance it seems something like this would work.
Also, you phrase the question as if you have a singular instance of a Post but then show your index action which would pull a collection of Posts. The example I provided would work for a singular Post (a user viewing the post's page).
I have a blogging application in which User has_many posts. I am using pagination with Booststrap. How can I make the partial_count method work with pagination? Currently, the count resets on every page instead of carrying over across pages.
posts_controller.rb
def index
#posts = Post.order("created_at desc").paginate(page: params[:page], :per_page => 12)
end
views/posts/index.html.erb
<%= render #posts %>
<%= will_paginate %>
views/posts/_post.html.erb
<%= post_counter +1%>
<%= post.name %>
The counter works fine on the first page. However, all subsequent pages also start with "1". How can I make subsequent pages start with (number of pages * 12 + 1) instead?
Thanks for your feedback!
Use #posts.offset to get the proper counter initialisation.
I'm creating a search page that will do an application wide search on users, posts, and comments. I currently have:
# POST /search
def index
query = params[:query]
#users = User.search(query).page(params[:page])
#posts = Post.search(query).page(params[:page])
#comments = Comment.search(query).page(params[:page])
respond_to do |format|
format.html
end
end
However I'm really trying to get something where all the results are mixed together then paginated. What are some of the strategies for doing paginated search like this? Thanks!
Ever since this commit: https://github.com/amatsuda/kaminari/commit/f9f529fb68ab89feea38773a4c625c1b14859128
You can do the following
In your view you can do this:
<%= paginate #users, :remote => true, :param_name => "user_page" %>
<%= paginate #posts, :remote => true, :param_name => "post_page" %>
<%= paginate #comments, :remote => true, :param_name => "comment_#{some_post_id}_page" %>
and then in your controller you can refer to them in this way:
#users = User.search(query).page(params[:user_page])
#posts = Post.search(query).page(params[:post_page])
#comments = Comment.search(query).page(params[:comment_page])
and your view's js.erb you might have something like:
$('#posts').html('<%= escape_javascript render(#posts) %>');
$('.table-pager').html('<%= escape_javascript(paginate(#posts, :remote => true).to_s) %>');
Before thinking about a solution, you need to first define exactly what you want the final result to be. If you want to display a few of each type of record on the results page you can modify the approach you posted and combine the three paginated results using:
#results = #users + #posts + #comments
#results.sort! { |a, b| a.score(query) > b.score(query) }
Each object will need to have an instance method 'score' that will let it sort based on the query priority. Also, you will need to modify your view to handle correct rendering of each item and ensure that the pagination is called on the model with the most pages.
Alternatively, a more robust method would be to add a full-text search service (such as Index Tank, Web Solr, Thinking Sphinx). The technology for what's hot for these moves quickly, so do some research and find one that fits your needs. Example syntax for this would be something like:
User.multi_solr_search query, models: [Post, Comment]
You could combine the results from the query and run page on that.
users = User.search(query)
posts = Post.search(query)
comments = Comment.search(query)
#results = users + posts + comments
#results.page(params[:page])
Ok so I have decided to use Kaminari for pagination in a rails 3 project. I have followed the video from RailsCasts http://railscasts.com/episodes/254-pagination-with-kaminari
All goes well up until the point or running the server.
controllers/stories_controller.rb
def index
#stories = Story.all
#pages = Story.page(params[:page]).per(3)
#stories = Story.search(params[:search])
end
views/stories/index.html.erb
<%= paginate #pages %>
When i start the server the index page in question displays all the stories from the DB and renders the pagination view showing (1 2 Next > Last ยป). What am I missing to get the pagination working?
I still can not understand your code. Why do you assign Story.all to #stories in the 1st line and overwrite the variable in the 3rd line?
Anyways, #stories will display "all the stories from the DB" because you're not calling the pagination method (.per) on #stories. The pagination links will show you the paginated counts because you're calling per method on #page variable and passing it to the helper.
I mean, you need to call .per on the relation before passing it to <%= paginate %> helper.
It's quite simple.
I guess you want to get results from your search, right?
Try
#stories = Story.search(params[:search]).page(params[:page]).per(3)
and something like:
<% #stories.each do |story| %>
<%= render story %>
<% end %>
<%= paginate #stories %>
in your view