Ruby on Rails: Display Number of Search Results Found - ruby-on-rails

I would like to display whatever number of items has been found and returned to the user. In my database, there are 4 items. The search feature works fine. What I now want to display is whatever number of records has been found. If user searches "aI", 2 items gets returned and I want to display the text that 2 items has been found. I tried to do that in view --> layout --> application.html.erb.

You have to count the actual results. Product (with a capital p) will always return all objects of that class in the database. Hence 26. Save the result in an ivar (#products) and call count on that in your view instead.
In Controller
#products = Product.fuzzy_search2(params[:search_string])
In View
<% if #products %>
<span> <%= #products.count %> Books Found</span>
<% end %>

I'm assuming that you are storing the search results in an ivar. You need to call .count on that ivar or .size / .length if it's stored in an array. The issue is that when you are calling Product.count you are getting the count of all products in your database always, because that's exactly what you are telling it to do.

Related

RAILS Active record search with multiple ordering -- out of order

I want to display reports that meet criteria and display them in a particular order.
Sort by user, then by report creation date of the report, newest on top
#report_results.order('created_at DESC, user_id')
Above is the code I use, however, when the data is displayed, toward the end of each user's reports, they start to show up out of order.
How do I Fix this?
View:
<% #report_results.order('created_at DESC, user_id').each do |report| %>
You could do:
variable = report_results.order('created_at DESC')
#report_results = variable.group_by(&:user_id)
This should return a hash of user_id with the respective reports ordered.
<% #report_results.order('user_id').order('created_at DESC').each do |report| %>
Not sure why this works, I thought the last order command would overwrite the previous, but it seems like it retains it.
Items now show up grouped by user_id, in descending chronological order.

Active Records - List the item's index number (the actual order number in which the item is displayed)

I'm a newb to Ruby on Rails and I have a issue trying to display the index number of a record set. I've had a good search, but can't find the specific answer.
The issue I'm having is that I cannot find a way to output the index number from a recordset which i'm displaying.
[Title], [Description]
[Title], [Description]
[Title], [Description]
etc.
So to clarify, I'm looking to output the order (index) number (1, 2, 3) in a list where i'm able to output the Title & Description, also i'll point out the obvious - this is different to the unique ID which may be stored in the database, thus if i was to filter or sort the results I would still want to show the order (index) number (1, 2, 3 etc).
I have founds example of where they loop through the results and incrementally add to a pre-defined index value. The problem is my app doesn't use a loop statement to output the records, instead it's using an Active Record to display (and essentially loop through) the results. From what I understand, Active records will automatically loop through and output the records by rendering the code snippet ie. <%= render #links %> This works great for my example - For the full code for the app, please refer to the tutorial I deprived the app from:
https://www.codementor.io/danielchinedu/building-a-basic-hacker-news-clone-with-rails-5-4gr4hrbis
So in retrospect, I'm looking to clone the app in the tutorial but add an order number to the link lists.
From the documentation:
Rails also makes a counter variable available within a partial called
by the collection, named after the member of the collection followed
by _counter.if you're rendering #products, within the partial you can
refer to product_counter to tell you how many times the partial has
been rendered.
guides.rubyonrails.org
So you can use something like <%= link_counter %> in your _link.html.erb partial. Hope this will help.
The tutorial actually explains it quiet well, i think.
Underneath the <%= render #links %>:
We are using a rails feature here, when you call render on an instance variable holding an active record relation object, it will iteratively loop through the object and then render the appropriate partial.
So! It's a Rails feature making it easier to write partial loops!
<%= render #links %> is the same as: <%= render partial: 'link', collection: #links %>
If you want an index in your partial, you can just append a local variable. For example:
<%= render #links, locals: {num: 1} %>
And then in your view after you have written the variable, remember to add 1 so it's ascending.
<div class="link">
<div class="title">
<%= num %>
<%= link_to link.title, (link.url? ? link.url : link) %>
...
<% num += 1 %>
Good luck!

Check whether a table column has any value

I have model named shirt which has a field named fabric,
In the controller I have;
#fabrics = Shirt.uniq.pluck(:fabric)
On the view I would like to display a <div>...</div> but only if the fabric column of the shirts table contains at least one value. I have tried:
<% if #fabrics != nil %>
<div>
...
</div>
<% end %>
But even when the whole column has no value, the <div> is still visible. I have also tried with
<%if #fabrics != blank %> with no success.
How can I check whether the column is not empty before rendering the div?
Try
<% unless #fabrics.blank? %>
Shirt.uniq.pluck(:fabric) returns a Relation. Therefore it will never be nil.
This Relation defines parts of a sql query. This says: Give me (all|one of the) unique values of fabric in the database. To actually run that query, you need to call a method on that relation that triggers the database call: all, first, each, any?, blank? ...
Through the lack of context, I do not know how you use your Shirt model. But I guess the query will never give you the expected answer. Because Shirt.uniq.pluck(:fabric) will always return something as long there is at least one row in that table. Imagine there is only one row in the table and it's fabric is nil, than Shirt.uniq.pluck(:fabric).blank? would determine Shirt.uniq.pluck(:fabric) to [nil]. And [nil].blank? == false
If you work on one specific shirt, use #shirt.fabric.present? If you want to know if there is at least one shirt in the db without a fabric Shirt.where(fabric: nil).any?
I recommend to read:
http://guides.rubyonrails.org/active_record_querying.html
http://api.rubyonrails.org/classes/ActiveRecord/Relation.html
Try this in controller
#fabrics = Shirt.uniq.pluck(:fabric).reject { |f| f.nil? || f.empty? }

Should I prepare the 'count' column when I'm showing the number of records each parent has?

I have Parent model and Child model.
Parent has many children.
In index.html.erb, I'm showing the number of records that each parent has.
But I bet it makes laggy when many people are accessing to this page at the same time.
<% #parents.each do |parent| %>
<td><%= parent.child.count %></td>
<% end %>
Should I create the column called 'count' in Parent table so that it won't need to calculate everytime it renders?
If this page, index.html.erb, will be often visited by your user, then I think you should make the 'count' column, maybe paired with counter cache, like this http://railscasts.com/episodes/23-counter-cache-column (sorry the video was old but it'll give you the idea).

View array or one record in rails view

In my method via some calculations a get data, then i need to view it in view, but if write
#ar.each do |a|
when i have only one record i get error, also when i have one error each is bad idea. So how to do this this?
So i have such code in method:
non_original = []
#articles.each do |a|
non_original << get_non_tecdoc("LA44", 1, "KNECHT")
end
#non_original = non_original
get_non_tecdoc returns object, or nothing...
So in view i have:
-#non_original.each do |no|
=no.brand
=no.description
=no.price
=no.quantity
But what to do if #non_original has one record, then #non_original.each gives error. So how to do check in view? If #non_original has one record, than simple #non_original.brand etc, but if more than one, than use each loop?
This will work with #ar as a single value as well as an array:
Array(#ar).each do |a|
p a
end
This Array is a method on Kernel.
<%= debug #ar %>
This will give you a nice YAML format to look at in your view (assuming ERB).
EDIT: I believe this is what you want, since you're not interested in debugging.
In your controller, use the splat operator to convert a singleton element to an array (it doesn't modify arrays):
#ar = *#ar
Then #ar.each will work as expected in your view.
Alternatively, you could check in your view:
<% if #ar.is_a?(Array) %>
<% #ar.each ... %>
<% else %>
<%= #ar %>
<% end%>
Why don't you try using #ar.inspect and output it to the console to see the instance variables contents.
As long as #ar is an array you should not get a error. If you are returning one record change it to an array with one record.
If you are using active record query interface like the "where" clause; it will return an array with 0 or more active_record objects. If you use find it will return one instance of an active_record object.
So if your method that queries is using the active record where clause #ar should always return an array.
Please try this:
Tablename.find_by_table_id
Example:
if account_id is 10 then, take following example,
#getResults = Account.find_by_account_id(10)
It will gives single record.
we can get values using #getResults.id,#getResults.name ....like wise.

Resources