I have created a custom method that will return unique items, together with the number of occurrences in a table. I have the following code:
#answers = Answer.all.count(:group => 'answer')
The result is fine when rendering it to JSON, showing:
{"0,0":1,"1,2":1,"2,2":1,"3,3":1}
...but I am unable to render the result to html. I can not display the key, values:
<% #answers.each do |answer| %>
<tr>
<td>key: <%= #answer.??? %></td>
<td>value: <%= #answer.??? %></td>
</tr>
<% end %>
If answers is a hash (and it looks like it is) you can pass the key and value into the rendering block by using two parameters instead of one.
like this:
<% #answers.each do |key, val| %>
<tr>
<td>key: <%= key %></td>
<td>value: <%= val %></td>
</tr>
<% end %>
Related
Hello i am new on ruby on rails.I am trying to build a page that have a date field, and after choosing a specific date, i want to generate a table that shows reports of this date select.
controllers/reports_controller.rb
class ReportsController < ApplicationController
def index
end
def test
#chosen_date = params[:report_date]
#incoming_messages = Message.where("inbound = 't' and created_at like '" + #chosen_date + "%'").count
#total_chats = Message.where("created_at like '" + #chosen_date + "%'").distinct.count(:phone_number)
#enrollment_by_andi = Enrollment.where("created_at like '" + #chosen_date + "%' and created_by = 'ANDI'").count
#enrollment_by_agent = Enrollment.where("created_at like '" + #chosen_date + "%' and created_by <> 'ANDI'").count
#sent_by_andi = Message.where("created_by = 'ANDI' and created_at like '" + #chosen_date + "%'").count
#sent_by_agents = Message.where("inbound = 'f' and created_by <> 'ANDI' and created_at like '" + #chosen_date + "%'").count
#unread_messages = Message.where("created_at like '" + #chosen_date + "%' and is_read = 'f'").distinct.count(:phone_number)
end
end
views/reports/index.html.erb
<h1>Reports</h1>
<%= form_tag(reports_test_path,:method => "post") do %>
<%= label_tag(:report_date,"Choose a Date") %>
<%= date_field_tag(:report_date)%>
<%= button_tag "Submit"%>
<% end %>
table i want to generate:
<table>
<th>
<td>Incoming Messages</td>
<td>Total Chats</td>
<td>Enrollment By Andi</td>
<td>Enrollment By Agent</td>
<td>Sent By Andi</td>
<td>Sent By Agents</td>
<td>Unread Messages</td>
</th>
<tr>
<td><%= #incoming_messages %></td>
<td><%= #total_chats %></td>
<td><%= #enrollment_by_andi %></td>
<td><%= #enrollment_by_agent %></td>
<td><%= #sent_by_andi %></td>
<td><%= #sent_by_agents %></td>
<td><%= #unread_messages %></td>
</tr>
</table>
Below is the image of the page:
Anyone can help me to find a method to generate a table under the date field when i press the button ?
You can use AJAX which goes really well with rails and is really decent. For this follow the following steps -
First create a partial _report_table.html.erb. You have a little problem in the table. So paste the below table html in the partial -
<table>
<tr>
<th>Incoming Messages</th>
<th>Total Chats</th>
<th>Enrollment By Andi</th>
<th>Enrollment By Agent</th>
<th>Sent By Andi</th>
<th>Sent By Agents</th>
<th>Unread Messages</th>
</tr>
<tr>
<td><%= #incoming_messages %></td>
<td><%= #total_chats %></td>
<td><%= #enrollment_by_andi %></td>
<td><%= #enrollment_by_agent %></td>
<td><%= #sent_by_andi %></td>
<td><%= #sent_by_agents %></td>
<td><%= #unread_messages %></td>
</tr>
</table>
create a js file as test.js.erb as your post method name is test which puts the table html in a div in index.html.erb
$('#report_table').html("<%= escape_javascript(render partial: 'report_table') %>");
add a div with report_table id in index.html.erb after the form
<div id="report_table"></div>
Add remote true in the form
form_tag(reports_test_path,:method => "post",:remote=>true)
add return in the test method which will render the required js file
respond_to do |format|
format.js
end
That should do it. Please let me know if you have any connfusion
You can submit the form by ajax by setting remote: true on the form tag:
<%= form_tag(reports_test_path,:method => "post", remote: true) do %>
<%= label_tag(:report_date,"Choose a Date") %>
<%= date_field_tag(:report_date)%>
<%= button_tag "Submit"%>
<% end %>
You then create a corresponding `app/views/reports/test.js.erb view file that generates the actual JavaScript code that will be sent and executed on the client side.
You can put the table in a partial, say app/views/reports/_table.html.erb and render it in the javascript:
var tableContainer = document.getElementById(...);
tableContainer.insertAdjacentHTML('beforeend', '<%= j render partial: "/reports/table" %>');
If you're not too familiar working with ajax and javascript, check out the Ruby on Rails guides
You can do this with server-side rendering
Add a template file with the following content:
views/reports/test.html.erb
<h1>Reports</h1>
<%# The date field from the index.html %>
<%= form_tag(reports_test_path,:method => "post") do %>
<%= label_tag(:report_date,"Choose a Date") %>
<%= date_field_tag(:report_date)%>
<%= button_tag "Submit"%>
<% end %>
<%# the new content %>
<table>
<th>
<td>Incoming Messages</td>
<td>Total Chats</td>
<td>Enrollment By Andi</td>
<td>Enrollment By Agent</td>
<td>Sent By Andi</td>
<td>Sent By Agents</td>
<td>Unread Messages</td>
</th>
<tr>
<td><%= #incoming_messages %></td>
<td><%= #total_chats %></td>
<td><%= #enrollment_by_andi %></td>
<td><%= #enrollment_by_agent %></td>
<td><%= #sent_by_andi %></td>
<td><%= #sent_by_agents %></td>
<td><%= #unread_messages %></td>
</tr>
</table>
You could reduce the repetition later on with partials and such, but that is not so important right now.
The more important problem is that your queries at least look you could do SQL injection with them (google for blog posts about "SQL injection active record rails"). Familiarize yourself with the ActiveRecord guides a bit more, things are more safe when you do it like this:
#chosen_date = Date.parse params[:report_date]
#incoming_messages = Message.where(inbound: 't').where(created_at: #chosen_date).count
Plus you don't need to write the SQL on your own.
Chaining the .where() leads to an AND in SQL and passing Date and Time objects (and Ranges) into the where() methods are improvements in the Rails releases from the later years
<tr>
<th><%=f.label(:id, "Choose car")%></th>
<td><%= f.select(:id, #cars_all.map{|c| [c.name, c.id]}) %></td>
</tr>
<tr>
<th><%=f.label(":list_id", "Choose List")%></th>
<td><%= f.select(:list_id, #lists.map{|s| [s.name, s.id]}) %></td>
</tr>
i want to get the value of these two select values to use them in the contorller to add them in the database in a joint table,
#car_id = params[:id]
doesn't work and doesn't get the data, and is there is away to echo these values
User can't able to directly access the parameter in controller it will be consist in any of the hash which will same name of form_for object_name
Suppose:
<%= form_for(#profile) do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= f.submit %>
<% end %>
So the parameter would be in the controller
"profile"=>{
"first_name"=>"Daniel",
"last_name"=>"Clark"
}
I would be accessible like in
params[:profile][:first_name]
So In your case please check the form_for object and access it through it.
You can access it through
params[form_for_object_hash_name][:id]
or try to put debugger on controller and check the correct params
I'm currently scraping product information from a website and am attempting to output it into a table on a webpage.
I'm stuck because the only code that I can get to properly format as
ITEM
IMAGE
PRICE
Is clearly wrong, and ends up replicating the data many times.
The partially functioning code is:
<table>
<tr>
<% #items.each do |title| %>
<% #images.each do |image| %>
<% #prices.each do |price| %>
<br>
<td><%= title %></td>
<br>
<td><%= image %></td>
<br>
<td><%= price %></td></tr>
<br>
</table>
<% end %>
<% end %>
<% end %>
I've tried formatting the code like below, but it tends to drop the three sets of data down like
TITLE TITLE TITLE IMAGE IMAGE IMAGE PRICE PRICE PRICE.
in a variety of very incorrect ways.
<table>
<tr>
<td>
<% #items.each do |title| %>
<%= title %>
<% end %>
</td>
<br>
<td>
<% #images.each do |image| %>
<%= image %>
<% end %>
<br>
<td>
<% #prices.each do |price| %>
<%= price %>
<% end %>
</td>
<br>
</table>
Is anyone able to spot the mistake I'm making or know what I need to do to properly output this code? Do I need to show you any more code?
If you want to iterate over the three arrays together you need to zip them. This will enable you to render each triplet together (the first item with the first image and the first price; the second item with the second image and the second price; etc.):
<table>
<% #items.zip(#images, #prices).each do |title, image, price| %>
<tr>
<td><%= title %></td>
<td><%= image %></td>
<td><%= price %></td>
</tr>
<% end %>
</table>
Is there a way to do this without javascript?
Let me explain. I have two models, users and dogs.
I'm using the index as a home page for when the users are logged in.
There is a form that searches dogs (not by any information the user enters, it's prepopulated with dog data), but the index is listing the result of my search query on page load. I'd like it to only show when the button is submitted.
I'll show some code.
controller for dog:
def index
if current_user
#user = current_user
#breed = #user.dogs.first.primarybreed
# params[:search] = #breed
#dog = Dog.search(params[:search]).sample
end
end
view:
%= form_tag dogs_path, :method => :get do %>
<%= hidden_field_tag :search, #breed %>
<%= image_submit_tag("/images/greenadd.png", size: "10x10", :name => nil) %> New Doggy Playdate!
<% end %>
<div id="dogswrap">
<h1><%= current_user.dogs[0].name %> Should Meet With...</h1>
<table>
<tbody>
<tr>
<td><%= image_tag #dog.image.url(:medium) %></td>
<td><%= #dog.name %></td>
<td><%= #dog.nick %></td>
<td><%= #dog.primarybreed %></td>
<td><%= #dog.secondarybreed %></td>
<td><%= #dog.age %></td>
<td><%= #dog.weight %></td>
<td><%= link_to "#{#dog.user.name}" %> </td>
<td><%= image_tag #dog.user.image.url(:thumb) %> </td>
</td>
</tr>
</tbody>
</table>
Model
def self.search(search)
find(:all, :conditions => ['primarybreed LIKE ?', "%#{search}%"])
end
I would like to have an if statement that shows the table only after the submit has been pushed.
If there is another way to do this, I'd appreciate it.
Thanks!
EDIT: Still working on this. May use a render..?
You can just use where in place of the way you're currently doing it find and conditions
def self.search(search)
where('primarybreed LIKE ?', "%#{search}%")
end
One thing I've learnt when using the LIKE function in development for SQLite3 and LIKE in PostgreSQL for production, was LIKE is case-insensitive in SQLite3 but not for PSQL. You would need to use ILIKE for that.
To your main question. This is how I would do it.
def index
if current_user
#user = current_user
#dogs = Dog.search(params[:search]) if params[:search].present?
end
end
For you views, start moving everything into a partial. _form.html.erb and _dog.html.erb
form
<%= form_tag dogs_path, :method => :get do %>
<%= text_field_tag :search %>
<%= image_submit_tag("/images/greenadd.png", size: "10x10", :name => nil) %> New Doggy Playdate!
<% end %>
dog
<td><%= image_tag dog.image.url(:medium) %></td>
<td><%= dog.name %></td>
<td><%= dog.nick %></td>
<td><%= dog.primarybreed %></td>
<td><%= dog.secondarybreed %></td>
<td><%= dog.age %></td>
<td><%= dog.weight %></td>
<td><%= link_to "#{dog.user.name}" %> </td>
<td><%= image_tag dog.user.image.url(:thumb) %></td>
Notice removed #dog and replaced with dog
Index view
<%= render 'form' %>
<div id="dogswrap">
<h1><%= #user.dogs[0].name %> Should Meet With...</h1>
<table>
<tbody>
<tr>
<% if #dogs %>
<%= render #dogs %>
<% end %>
</tr>
</tbody>
</table>
changed current_user.dogs[0].. to #user.dogs[0].. Also made a conditional for if the #dogs instance variable is truthy. If it is, then render will render out the _dog.html.erb partial for each dog in the #dogs collection
I have a hash of images that i'd like to output via a html table.
It's a basic task that I've done in PHP but I'd like to see what magical stuff ruby can do to achieve it easily.
I've looked at helpers and tutorials and they're all very complicated.
Here's how I am currently printing the images.. How would I convert it to output to something like a 4 x n table?
<% #photos.each do |photo| %>
<%= image_tag photo["images"][4]["source"] %><br/>
<% end %>
Take a look at the each_slice method, which lets you grab your array in groups of a given size. You should be able to do something like
<table>
<% #photos.each_slice(4) do |group| %>
<tr>
<%group.each do |photo|%>
<td>
<%= image_tag photo["images"][4]["source"] %>
<td>
<% end %>
</tr>
<% end %>
</table>
I think in_groups_of might help you out:
<table>
<% #photos.in_groups_of(4, false) do |photos| %>
<tr>
<% photos.each do |photo| %>
<td><%= image_tag photo["images"][4]["source"] %></td>
<% end %>
</tr>
<% end %>
</table>
By passing false as the second argument, the last row might be incomplete. If you want to show a blank image instead, you can pass an empty photo object (assuming its URI points to the blank image your website is using) or simply the direct URI, if the photos array is only an array of URIs.