Rails: Controller dumps data in view - ruby-on-rails

I have a simple controller with def index having the following code:
#companies = Company.all
respond_to do |format|
format.html
end
But in the view I get these errors appended after all the companies are being displayed:
[#<Company id: 4, title: "Testing #1(1)", created_at: "2013-02-05 19:14:04", updated_at: "2013-02-05 19:14:04">, #<Company id: 7, title: "Testing #1 1", created_at: "2013-02-05 19:34:48", updated_at: "2013-02-05 19:34:48">]
Updated with the view code:
= #companies.each do |company|
%li
.box
.c
%h2
= link_to company.title, company

= #companies.each do |company|
The equals sign in Haml means "print the result of this expression." You're seeing the array of companies on the page because you asked for it.
Use a hyphen instead.
- #companies.each do |company|

Related

Ruby on rails incorrectly dumps all the postgresql table content

I'm realatively new to ruby on rails and im really having problems with a simple for-loop.
I'm doing this:
Inside posts_controller.rb
#post = Post.all.order("created_at DESC")
Inside posts/index.html.erb (the view related to the controller)
<%= #post.each do |post| %>
<%= link_to post.title, post %>
<br>"Published "
<%= time_ago_in_words(post.created_at) %>
<br>by user.email
<%= post.user.email %>
<br><br>
<% end %>
But the output is (I copied just the important part)
primer pst de ET
"Published " 1 day
by user.email cacaca#gmail.com
primer post de cocina
"Published " 1 day
by user.email cacaca#gmail.com
[#<Post id: 14, title: "La tercera es la vencida", content: "<p><span style=\"color:#ffffff;\"><span style=\"backg...", created_at: "2018-12-23 03:07:41", updated_at: "2018-12-23 03:07:41", user_id: 1, category: "rangos de aventurero", thumbnail: "img2", status: "pending">, #<Post id: 13, title: "segundo post con status", content: "<p><span style=\"color:#2ecc71;\">ahora ´si qu...", created_at: "2018-12-23 03:05:32", updated_at: "2018-12-23 03:05:32", user_id: 1, category: "Endless Tower", thumbnail: nil, status: nil>, #<Post id: 12, title: "Segundo post COCINA", content: "<p>Esto es el primer post COCINA con imágen...", created_at: "2018-12-23 02:53:06", updated_at: "2018-12-23 02:53:06", user_id: 1, category: "Cocina", thumbnail: nil, status: nil>, #<Post id: 11, title: "primer post con status", content: "gtgtrhtgr", created_at: "2018-12-23 02:31:51", updated_at: "2018-12-23 02:31:51", user_id: 1, category: "", thumbnail: nil, status: nil>, #<Post id: 10, title: "primer post economía", content: "f3rggg ecoooooo", created_at: "2018-12-23 02:19:42", updated_at: "2018-12-23 02:19:42", user_id: 1, category: "Economía", thumbnail: nil, status: nil>, #<Post id: 9, title: "primer pst de ET", content: "ET SE HACE UNA VEZ A LA SEMAN", created_at: "2018-12-23 02:17:04", updated_at: "2018-12-23 02:17:04", user_id: 1, category: "Endless Tower", thumbnail: nil, status: nil>, #<Post id: 8, title: "primer post de cocina", content: "wfowrffmweew COCINAAAAAA", created_at: "2018-12-23 02:00:39", updated_at: "2018-12-23 02:00:39", user_id: 1, category: "Cocina", thumbnail: nil, status: nil>]
AQUÍ TERMINA EL RENDER INDIVIDUAL
So it dumps all the database content at the end and I realy don't know why.
I clearly don't want the user to see the table content but I don't know whats wrong with the code above.
I know it's probably a very basic question, but i can't find the answer yet. Please help me.
Thanks for yor help :)
EDIT: here is the full controller code
class PostsController < ApplicationController
# La siguiente línea establece que se llamará al método <find_post>
# antes de llamar a los métodos <show>, <edit>, <update>, <destroy>
before_action :find_post, only: [:show, :edit, :update, :destroy]
before_action :stablish_categories_and_thumbnail
def index
#post = Post.all.order("created_at DESC")
end
def show
end
def new
#post = current_user.posts.build
end
def create
#post = current_user.posts.build(post_params)
if #post.save
redirect_to #post
else
render 'new'
end
end
def edit
end
def update
if #post.update(post_params)
redirect_to #post
else
render 'edit'
end
end
def destroy
#post.destroy
redirect_to root_path
end
private
def post_params
params.require(:post).permit(:title, :content, :category, :status, :thumbnail)
end
def find_post
#post = Post.find(params[:id])
end
def stablish_categories_and_thumbnail
# Esto es lo que hay que ir rellenando luego con las categorías finales
#categories = ['Cocina',
'Endless Tower',
'Economía',
'rangos de aventurero']
#thumbnails_list = ['img1', 'img2', 'img3', 'img4']
end
end
Remove the = sign from your posts/index.html.erb:
<% #post.each do |post| %>
instead of
<%= #post.each do |post| %>
<%= ... %> will evaluate the statement/block and print the result. <% ... %> will only evaluate and not print it. For example -
<%= a = 5 %> will assign and print '5' on the page.
<% a = 5 %> will only assign '5' to the local variable a but not print it.

Why do I receive undefined method after dynamically building array of Objects? Ruby

I'm building a most viewed post feature for a simple blog. Each post has a view count that is increased when the Show action is called for that particular post. Then on the Dashboard , I'm trying to list the top 5 posts. So far my code works and returns an array of posts with the post with the highest number of view count being the first index and the last index in the array being the post with the lowest view count. The only thing is when I try to iterate through the array in the view , the view returns:
ERROR
undefined method `title' for nil:NilClass
WHY??? Does it have to do with the "#" infront of the object?
Heres my code.
Dashboard View
<h3> Post </h3>
<% #top_posts.each do |post| %>
<%= post.title %>
<% end %>
Controller Methods
def get_top
#top_posts = []
counts = []
#posts = Post.all
#posts.each do |post|
counts << post.view_count
end
#posts.each do |post|
if counts.max(5).include?(post.view_count)
counts.max(5).each do |n|
if n == post.view_count
#top_posts[counts.max(5).index(n)] = post
end
end
end
end
end
def dashboard
#posts = Post.all
get_top
end
The Top Podcast Array of objects
[#<Post id: 6, title: "Post 6", desc: "", tags: "", view_count: 8, s_desc: "", c_photo: nil, photos: nil, created_at: "2017-06-14 06:02:25", updated_at: "2017-06-15 01:38:40", featured: nil>, #<Post id: 3, title: "post 3", desc: "", tags: "", view_count: 5, s_desc: "", c_photo: nil, photos: nil, created_at: "2017-06-14 05:35:32", updated_at: "2017-06-14 05:35:53", featured: nil>, #<Post id: 5, title: "Post 5", desc: "", tags: "", view_count: 4, s_desc: "", c_photo: nil, photos: nil, created_at: "2017-06-14 06:02:20", updated_at: "2017-06-15 01:38:31", featured: nil>, nil, #<Post id: 4, title: "Post 4", desc: "", tags: "", view_count: 3, s_desc: "", c_photo: nil, photos: nil, created_at: "2017-06-14 05:49:29", updated_at: "2017-06-15 01:38:50", featured: nil>]
The other answer would probably solve your error, but just want to make an attempt to optimize your code.
That array, loop, etc. is unnecessary, ask your db to do that stuff and get the top posts. Fetching all posts and looping over it multiple times...nay, try the following, hopefully this is what you are looking for..
#top_posts = Post.order('view_count desc').limit(5)
That's it, your view needs no change and will work as expected.
Try:
#top_posts << post
instead of:
#top_posts[counts.max(5).index(n)] = post
You don't need to set the array index.

Passing params to rails action mailer

I am using action mailer to email winners, #result array has records of participants who has won including their email.
#result=>[#<Participant id: 47, admin_id: nil, sweepstake_id: 8, participant_name: "gomez", participant_email: "rakesh.k#birdvision.in", participant_number: "12131245421", ip_addr: "127.0.0.1", answer: "nice", reg_time: nil, entry_opt_id: nil, created_at: "2015-09-03 12:15:48", updated_at: "2015-09-07 12:12:53">, #<Participant id: 47, admin_id: nil, sweepstake_id: 8, participant_name: "gomez", participant_email: "rakesh.k#birdvision.in", participant_number: "12131245421", ip_addr: "127.0.0.1", answer: "nice", reg_time: nil, entry_opt_id: nil, created_at: "2015-09-03 12:15:48", updated_at: "2015-09-07 12:12:53">]
But when i pass the result from my controller to the mailer, the result now only has id as string.
Parameters: {"result"=>["47", "47"]}.
How can i pass the array result which has all the participant records?
Code in view page:
<%= link_to "Email Winners",email_winner_sweepstakes_path(:result=>#result) %>
Code in controller:
def email_winner
Rails.logger.info("***********************#{params.inspect}")
ParticipantMailer.winner_confirmation(params[:result]).deliver_now!
end
Code in mailer:
def winner_confirmation(result)
#result = result
#url = 'http://example.com/login'
Rails.logger.info("=================mailer=================")
Rails.logger.info(#result.inspect)
#result.each do |i|
mail(to: i.participant_email, subject: 'Congratulation')
end
end
You will have to find winners by ID, in this line:
<%= link_to "Email Winners", email_winner_sweepstakes_path(result: #result) %>
what you do is formulate the URL and you can't store objects its only string and what it did is it will call .id on #result
to fix that:
in your controller:
def email_winner
#results = Participant.where("id in (?)", params[:result])
ParticipantMailer.winner_confirmation(#results).deliver_now!
end
You cannot pass ruby objects in links, because that triggers a new page load on a different URI, and the ids are provided in that address. You need to only pass ids.
Therefore your ids being passed here, you can fetch the objects with the following:
#result.each do |id|
participant = Participant.find(id)
mail(to: participant.participant_email, subject: 'Congratulation')
end

Why is rails dumping data to the page on each

I have a simple controller called list_controller with an index that basically does
def index
#lists = List.all
end
Then i have a view called index.html.haml that looks like:
%h1 My lists
= #lists.each do |list|
.row-fluid
%h2= list.title
%p= list.description
%hr
= link_to "New list", new_list_url
This works and renders but at the bottom of my list is what appears to be a ruby print of the lists objects, in this case a nice big ugly:
[#<List id: 1, title: "Petes todo list", description: "This is petes main list, all sorts of good stuff", created_at: "2012-03-26 21:42:57", updated_at: "2012-03-26 21:42:57">, #<List id: 2, title: "Petes work list", description: "A list for petes work stuff", created_at: "2012-03-26 22:09:50", updated_at: "2012-03-26 22:09:50">]
Why is this happening? How can I stop it?
You're outputting the result of the each, change:
= #lists.each do |list|
to:
- #lists.each do |list|
Haml documentation: = vs -
= #lists.each do |list| tells Haml to evaluate Ruby code to the right and then print out the return value. You should rewrite your view to
%h1 My lists
- #lists.each do |list|
.row-fluid
%h2= list.title
%p= list.description
%hr
= link_to "New list", new_list_url

In my Rails app, JSON formatted results are appearing in a HTML view response

In a Rails 3.1 app, I have a controller returning a set of objects (children) in an index view using this code:
def index
#children = Child.all
#base_class = "children-index"
#title = "Your Children"
respond_to do |format|
format.html # children/index.html.erb
format.json { render :json => #children }
end
end
The index.html.erb view is written like so:
<h1><%= title %></h1>
<ul>
<%= #children.each do |child| %>
<li><%= link_to child.fullname, child_path(child) %></li>
<% end %>
</ul>
For some reason, the JSON response is getting thrown into the HTML response and I cannot determine the reason. None of my other index views are having this issue and their code is very close to the same.
John Jake Smith Jr
Jane Ann Doe
[#<Child id: 1, firstname: "John", middlename: "Jake", lastname: "Smith", suffix: "Jr", gender: "Male", dob_actual: "2011-01-05", dob_expected: "2011-01-01", height: 30, weight: 40, created_at: "2011-10-28 21:32:54", updated_at: "2011-10-28 21:32:54">, #<Child id: 2, firstname: "Jane", middlename: "Ann", lastname: "Doe", suffix: "", gender: "Female", dob_actual: "2011-05-05", dob_expected: "2011-05-01", height: 30, weight: 12, created_at: "2011-11-07 18:08:54", updated_at: "2011-11-07 18:08:54">]
That's not JSON, that's inspect output. You're getting that because each returns #children and you're using <%= here:
<%= #children.each do |child| %>
You want just this:
<% #children.each do |child| %>
Did you forget to do #children.to_json in your controller?

Resources