undefined method `each' for nil:NilClass error in comment - ruby-on-rails

In my application is a blog, and under post you can write comment.
My problem is when i want delete the comment show this error.
undefined method `each' for nil:NilClass
How to fix this problem?
comment_controller :
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
def create
#link = Link.find(params[:link_id])
#comment = #link.comments.new(comment_params)
#comment.user = current_user
respond_to do |format|
if #comment.save
format.html { redirect_to #link, notice: 'comment was successfully create'}
format.json { render json: #comment, status: :created, location: #comment }
else
format.html { render action: 'new' }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
def destroy
#comment.destroy
respond_to do |format|
format.html {redirect_to comments_url, notice: 'Comment was successfully destroyed.'}
format.json {head :no_content}
end
end
private
def set_comment
#comment = Comment.find(params[:id])
end
def comment_params
params.require(:comment).permit(:link_id, :body, :user_id)
end
end
after try to delete comment log this in terminal:
Started GET "/comments" for ::1 at 2015-02-28 11:52:51 +0330
Processing by CommentsController#index as HTML
Rendered comments/index.html.erb within layouts/application (2.1ms)
Completed 500 Internal Server Error in 8ms
ActionView::Template::Error (undefined method `each' for nil:NilClass):
13: </thead>
14:
15: <tbody>
16: <% #comment.each do |comment| %>
17: <tr>
18: <td><%= comment.body %></td>
19: <td><%= comment.user %></td>
app/views/comments/index.html.erb:16:in `_app_views_comments_index_html_erb__2236689348233653025_70351465687200'
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_source.erb (8.9ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_trace.html.erb (2.9ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_request_and_response.html.erb (0.8ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_web_console.html.erb (0.8ms)
Rendered /Library/Ruby/Gems/2.0.0/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/template_error.html.erb within rescues/layout (26.2ms)
Comment index.html.erb
<p id="notice"><%= notice %></p>
<h1>Listing Comments</h1>
<table>
<thead>
<tr>
<th>Link</th>
<th>Body</th>
<th>User</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #comments.each do |comment| %>
<tr>
<td><%= comment.body %></td>
<td><%= comment.user %></td>
<td><%= link_to 'Show', comment %></td>
<td><%= link_to 'Edit', edit_comment_path(comment) %></td>
<td><%= link_to 'Destroy', comment, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Comment', new_comment_path %>

I guess, It should be, Please cross check
<% #comments.each do |comment| %>
Controller Code
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
def index
#comments = Comment.all
end
def destroy
post = Post.where(id: params[:post_id]).take
post.comments.find(params[:id]).destroy
respond_to do |format|
format.html {redirect_to post_url, notice: 'Comment was successfully destroyed.'}
format.json {head :no_content}
end
end
Try this

Related

undefined method `each' for nil:NilClass. The views and the controller match up

I have looked all over on stack overflow to try to fix this problem and I can't seem to find a fix. I can include more code if needed.
I tried changing in the controller to comment to comments and that does not change anything.
I tried changing to comments to comment and that does not change anything.
I am legit stuck on this and I want to know why this is happening. Thanks
Comments_controller
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
# GET /comments
# GET /comments.json
# POST /comments
# POST /comments.json
def create
#pin = Pin.find(params[:pin_id])
#comments = #pin.comments.new(comment_params)
#comment.user = current_user
respond_to do |format|
if #comment.save
format.html { redirect_to #comment, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: #comment }
else
format.html { render :new }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /comments/1
# PATCH/PUT /comments/1.json
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
#comment.destroy
respond_to do |format|
format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
#comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:pin_id, :body, :user_id)
end
end
My index.html.erb
<h1>Listing comments</h1>
<table>
<thead>
<tr>
<th>Link</th>
<th>Body</th>
<th>User</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #comments.each do |comment| %>
<tr>
<td><%= comment.link_id %></td>
<td><%= comment.body %></td>
<td><%= comment.user %></td>
<td><%= link_to 'Show', comment %></td>
<td><%= link_to 'Edit', edit_comment_path(comment) %></td>
<td><%= link_to 'Destroy', comment, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Comment', new_comment_path %>
Add an index method to the controller:
def index
#comments = Comment.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #comments }
end
end

ActiveRecord::RecordNotFound in TodosController#index

The full text of the error message is:
ActiveRecord::RecordNotFound in TodosController#index
Couldn't find User with id=2
Rails.root: /home/randy/rubystack-1.9.3-29/projects/chap14
app/controllers/application_controller.rb:11:in current_user
app/views/todos/index.html.erb:21:in _app_views_todos_index_html_erb___949818655437808348_39324440
app/controllers/todos_controller.rb:8:in index
Here's the code for my application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user
private
def current_user
if session[:user_id]
#current_user ||= User.find(session[:user_id])
else
#current_user = nil
end
end
def check_login
unless authorized?
redirect_to "/auth/identity"
end
end
def logged_in?
if session[:user_id]
return true
else
return false
end
end
protected
def authorized?
logged_in? && (request.get? || current_user.admin?)
end
end."
And here's my todos_controller.rb:
class TodosController < ApplicationController
before_filter :check_login
# GET /todos
# GET /todos.json
def index
#todos = Todo.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #todos }
end
end
# GET /todos/1
# GET /todos/1.json
def show
#todo = Todo.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #todo }
end
end
# GET /todos/new
# GET /todos/new.json
def new
#todo = Todo.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #todo }
end
end
# GET /todos/1/edit
def edit
#todo = Todo.find(params[:id])
end
# POST /todos
# POST /todos.json
def create
#todo = Todo.new(params[:todo])
respond_to do |format|
if #todo.save
format.html { redirect_to #todo, notice: 'Todo was successfully created.' }
format.json { render json: #todo, status: :created, location: #todo }
else
format.html { render action: "new" }
format.json { render json: #todo.errors, status: :unprocessable_entity }
end
end
end
# PUT /todos/1
# PUT /todos/1.json
def update
#todo = Todo.find(params[:id])
respond_to do |format|
if #todo.update_attributes(params[:todo])
format.html { redirect_to #todo, notice: 'Todo was successfully updated.' }
format.json { head :no_content }
#todo = Todo.find(params[:id])
if #todo.completed == true
#todo.user_who_completed = current_user.email
#todo.save
end
else
format.html { render action: "edit" }
format.json { render json: #todo.errors, status: :unprocessable_entity }
end
end
end
# DELETE /todos/1
# DELETE /todos/1.json
def destroy
#todo = Todo.find(params[:id])
#todo.destroy
respond_to do |format|
format.html { redirect_to todos_url }
format.json { head :no_content }
end
end
end."
And my app/views/todos/index.html.erb file:
"<h1>Listing todos</h1>
<table>
<tr>
<th>Name</th>
<th>Completed</th>
<th>Completed date</th>
<th>User</th>
<th></th>
<th></th>
<th></th>
</tr>
<% for todo in #todos %>
<tr>
<td><%= todo.name %></td>
<td><%= todo.completed %></td>
<td><%= todo.completed_date %></td>
<td><%= todo.user %></td>
<% end %>
<% if current_user.admin? %>
<td><%= link_to 'Show', todo %></td>
<td><%= link_to 'Edit', edit_todo_path(todo) %></td>
<td><%= link_to 'Destroy', todo, method: :delete, data: { confirm: 'Are you sure?' } %></td>S
</tr>
<% end %>
</table>
<br />
<% if current_user.admin? %>
<%= link_to 'New Todo', new_todo_path %>
<% end %>
I'm new to rails and have no clue about what the error message means, nor its cause. I want the visitor to land on the todos/index.html page. I have my root route set accordingly. Would appreciate some help.
That error is coming from User.find. It's described in the Documentation for find.
It's telling you that there is no User that has that id. Somehow you have saved a user id into your session that corresponds to a user that doesn't currently exist.
You should probably examine how you are storing user ids to the session and under what circumstances that user could be getting deleted.
The problem is with your loop. If conditional it is outside the cycle.
Check solution view:
<h1>Listing todos</h1>
<table>
<tr>
<th>Name</th>
<th>Completed</th>
<th>Completed date</th>
<th>User</th>
<th></th>
<th></th>
<th></th>
</tr>
<% for todo in #todos %>
<tr>
<td><%= todo.name %></td>
<td><%= todo.completed %></td>
<td><%= todo.completed_date %></td>
<td><%= todo.user %></td>
<% if current_user.admin? %>
<td><%= link_to 'Show', todo %></td>
<td><%= link_to 'Edit', edit_todo_path(todo) %></td>
<td><%= link_to 'Destroy', todo, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>
</tr>
<% end %>
</table>
Recommendations
Check your question. You have the code view with the controller code.
Be careful with indentation.

No Method Error in Japas#index

I generated a scaffold called rounds. Here is what my JapasController looks like:
class JapasController < ApplicationController
before_action :set_japa, only: [:show, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
#japas = Japa.all
#users = User.all
end
def show
end
def new
#japa = current_user.japas.build
end
def edit
end
def create
#japa = current_user.japas.build(japa_params)
respond_to do |format|
if #japa.save
format.html { redirect_to #japa, notice: 'Japa was successfully created.' }
format.json { render :show, status: :created, location: #japa }
else
format.html { render :new }
format.json { render json: #japa.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #japa.update(japa_params)
format.html { redirect_to #japa, notice: 'Japa was successfully updated.' }
format.json { render :show, status: :ok, location: #japa }
else
format.html { render :edit }
format.json { render json: #japa.errors, status: :unprocessable_entity }
end
end
end
def destroy
#japa.destroy
respond_to do |format|
format.html { redirect_to japas_url, notice: 'Japa was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_japa
#japa = Japa.find(params[:id])
end
def correct_user
#japa = current_user.japas.find_by(id: params[:id])
redirect_to japas_path, notice: "Not authorized to edit this japacount" if #japa.nil?
end
# Never trust parameters from the scary internet, only allow the white list through.
def japa_params
params.require(:japa).permit(:rounds, :comment, :user_id)
end
end
Japa Model:
class Japa < ActiveRecord::Base
belongs_to :user
end
User Model:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :japas
end
Here is my index template for Japas:
<p id="notice"><%= notice %></p>
<center>
<h1>Listing Japa</h1>
<table class = 'table table-hover' style = 'width:700px;'>
<thead>
<tr>
<th>Time</th>
<th>Rounds</th>
<th>Goal</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #users.each do |user| %>
<tr>
<td><%= user.japas.created_at %></td>
<td><%= user.japas.rounds %></td>
<td> / 16 </td>
<td><%= link_to 'Show', japa %></td>
<% if japa.user == current_user %>
<td><%= link_to 'Edit', edit_japa_path(japa) %></td>
<td><%= link_to 'Destroy', japa, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<%end%>
</tr>
<tr>
<td>Total Sum</td>
</tr>
<% end %>
</tbody>
</table>
</center>
<br>
<% if user_signed_in? %>
<%= link_to 'New Japa', new_japa_path %>
<%end%>
Here is my error message when I load: http://localhost:3000/japas.
NoMethodError in Japas#index
Showing /Users/vvd/Desktop/japacounter/app/views/japas/index.html.erb where line #20 raised:
undefined method `created_at' for #<User:0x007f981a4536e8>
Extracted source (around line #20):
<% #users.each do |user| %>
<tr>
<td><%= user.japas.created_at %></td>
<td><%= user.japas.rounds %></td>
<td> / 16 </td>
This is a picture of the error page I am receiving:
Based on your requirements on comments you can try this on.
You have to change your controller action as following for getting japas for the current_user
def index
#japas = Japa.where(user_id: current_user.id)
end
And in view iterate with #japas, as following
<% #japas.each do |japa| %>
<tr>
<td><%= japa.created_at %></td>
<td><%= japa.rounds %></td>
</tr>
<% end %>
You can not call an attribute/method like created_at with an active record associations collection. User has many Japa, so you can re-write you view as following in error area with rest of your code. Just iterate within user.japas.
<% #users.each do |user| %>
<% user.japas.each do |japa| %>
<tr>
<td><%= japa.created_at %></td>
<td><%= japa.rounds %></td>
</tr>
<% end %>
<% end %>

I do not understand this Rails SyntaxError

I'm just beginning to work through Agile Web Development with Rails, 4th Edition, and I've run into a SyntaxError while setting up my first application in Chapter 6. The code is below as well as the error. I'm running Ruby 1.9.3 and Rails 3.2.1.3. I tried to follow the book exactly, so I'm not sure where I'm going wrong. I saw a similar error on this question but it did not fix my problem.
Here is the index.html for Product
<h1>Listing products</h1>
<table>
<tr>
<th>\</th>
<th>Title</th>
<th>Description</th>
<th>Image url</th>
<th>Price</th>
<th></th>
<th></th>
<th></th>
</tr>
<% #products.each do |product| %>
<tr>
<td><%= product.\ %></td>
<td><%= product.title %></td>
<td><%= product.description %></td>
<td><%= product.image_url %></td>
<td><%= product.price %></td>
<td><%= link_to 'Show', product %></td>
<td><%= link_to 'Edit', edit_product_path(product) %></td>
<td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Product', new_product_path %>
And here is the error that I'm getting
SyntaxError in Products#index
Showing C:/Sites/work/depot/app/views/products/index.html.erb where line #17 raised:
C:/Sites/work/depot/app/views/products/index.html.erb:17: syntax error, unexpected $undefined
...tput_buffer.append= ( product.\ );#output_buffer.safe_concat...
... ^
C:/Sites/work/depot/app/views/products/index.html.erb:26: syntax error, unexpected keyword_end, expecting ')'
'); end
^
C:/Sites/work/depot/app/views/products/index.html.erb:33: syntax error, unexpected keyword_ensure, expecting ')'
C:/Sites/work/depot/app/views/products/index.html.erb:35: syntax error, unexpected keyword_end, expecting ')'
Extracted source (around line #17):
14:
15: <% #products.each do |product| %>
16: <tr>
17: <td><%= product.\ %></td>
18: <td><%= product.title %></td>
19: <td><%= product.description %></td>
20: <td><%= product.image_url %></td>
Trace of template inclusion: app/views/products/index.html.erb
Rails.root: C:/Sites/work/depot
Update to add the model file for Product and the error for removing the <%= product.\ %> lines per comments below.
class Product < ActiveRecord::Base
attr_accessible :\, :description, :image_url, :price, :title
end
NoMethodError in Products#index
Showing C:/Sites/work/depot/app/views/products/index.html.erb where line #15 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #15):
12: <th></th>
13: </tr>
14:
15: <% #products.each do |product| %>
16: <tr>
17:
18: <td><%= product.title %></td>
Rails.root: C:/Sites/work/depot
Further edited to add Controller file
class ProductsController < ApplicationController
# GET /products
# GET /products.json
def index
#products = Product.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #products }
end
end
# GET /products/1
# GET /products/1.json
def show
#product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #product }
end
end
# GET /products/new
# GET /products/new.json
def new
#product = Product.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #product }
end
end
# GET /products/1/edit
def edit
#product = Product.find(params[:id])
end
# POST /products
# POST /products.json
def create
#product = Product.new(params[:product])
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render json: #product, status: :created, location: #product }
else
format.html { render action: "new" }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# PUT /products/1
# PUT /products/1.json
def update
#product = Product.find(params[:id])
respond_to do |format|
if #product.update_attributes(params[:product])
format.html { redirect_to #product, notice: 'Product was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.json
def destroy
#product = Product.find(params[:id])
#product.destroy
respond_to do |format|
format.html { redirect_to products_url }
format.json { head :no_content }
end
end
end
modify #products.each to #product.each. And delete line of "\".

Learning Ruby on Rails. Syntax issue

I'm new to Ruby, Rails and programming in general, so please forgive me if the question is very trivial.
I have this view:
<h1>Listing products</h1>
<table>
<tr>
<th>\</th>
<th></th>
<th></th>
<th></th>
</tr>
<% #products.each do |product| %>
<tr>
<td><%= product.\ %></td>
<td><%= link_to 'Show', product %></td>
<td><%= link_to 'Edit', edit_product_path(product) %></td>
<td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Product', new_product_path %>
When I try to access the link http://localhost:3000/products I receive an error:
SyntaxError in Products#index
Showing C:/Sites/depot/app/views/products/index.html.erb where line #13 raised:
C:/Sites/depot/app/views/products/index.html.erb:13: syntax error, unexpected $undefined
...tput_buffer.append= ( product.\ );#output_buffer.safe_concat...
... ^
C:/Sites/depot/app/views/products/index.html.erb:18: syntax error, unexpected keyword_end, expecting ')'
'); end
^
C:/Sites/depot/app/views/products/index.html.erb:25: syntax error, unexpected keyword_ensure, expecting ')'
C:/Sites/depot/app/views/products/index.html.erb:27: syntax error, unexpected keyword_end, expecting ')'
Extracted source (around line #13):
10:
11: <% #products.each do |product| %>
12: <tr>
13: <td><%= product.\ %></td>
14: <td><%= link_to 'Show', product %></td>
15: <td><%= link_to 'Edit', edit_product_path(product) %></td>
16: <td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>
Trace of template inclusion: app/views/products/index.html.erb
I was just following an example in a book to learn Rails, so basically I've done nothing to code this view.
Can someone point me to the right direction?
You need to put <%= product.name %> (substitute in desired attribute) instead of <%= product.\ %>
The little tiny caret under the the incorrect syntax gives you an indication of what is tripping the error.
Rewrite the code # app\views\products\index.html.erb" as follows:
<h1>Listing products</h1>
<table>
<% #products.each do |product| %>
<tr class="<%= cycle('list_line_odd', 'list_line_even') %>">
<td>
<%= image_tag(product.image_url, class: 'list_image') %>
</td>
<td class="list_description">
<dl>
<dt><%= product.title %></dt>
<dd><%= truncate(strip_tags(product.description),
length: 80) %></dd>
</dl>
</td>
<td class="list_actions">
<%= link_to 'Show', product %><br/>
<%= link_to 'Edit', edit_product_path(product) %><br/>
<%= link_to 'Destroy', product, method: :delete,
data: { confirm: 'Are you sure?' } %>
</td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New product', new_product_path %>
Rewrite the code # app\controllers\products_controller.rb as follows:
class ProductsController < ApplicationController
# GET /products
# GET /products.json
def index
#products = Product.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #products }
end
end
# GET /products/1
# GET /products/1.json
def show
#product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #product }
end
end
# GET /products/new
# GET /products/new.json
def new
#product = Product.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #product }
end
end
# GET /products/1/edit
def edit
#product = Product.find(params[:id])
end
# POST /products
# POST /products.json
def create
#product = Product.new(params[:product])
respond_to do |format|
if #product.save
format.html { redirect_to #product,
notice: 'Product was successfully created.' }
format.json { render json: #product, status: :created,
location: #product }
else
format.html { render action: "new" }
format.json { render json: #product.errors,
status: :unprocessable_entity }
end
end
end
# PUT /products/1
# PUT /products/1.json
def update
#product = Product.find(params[:id])
respond_to do |format|
if #product.update_attributes(params[:product])
format.html { redirect_to #product,
notice: 'Product was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #product.errors,
status: :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.json
def destroy
#product = Product.find(params[:id])
#product.destroy
respond_to do |format|
format.html { redirect_to products_url }
format.json { head :no_content }
end
end
end
rails generates very useful logs. Read it once it gives you line number and file name.
replace <%= product.\%> with <%= product.name %> where name is the attribute of product.

Resources