undefined method `each' for nil:NilClass..why? - ruby-on-rails

i've been working on new app it's like IMDB and i added category model which it works fine with the association but i'm having problem in Displaying movies by category in category controller:
def show
#category = Category.find(params[:id])
#category_movies = #category.movies
end
in the category show page:
<h align = "center"><%= "Category: " + #category.name %></h1>
<%= render 'movies/movies', obj:#category_movies %>
and in index i did:
<div class= "row">
<% #movies.each do |movie|%>
<div class="col-sm-6 col-md-3">
<div class="thumbnail">
<%= link_to (image_tag movie.image.url(:medium), class: 'image'), movie %>
</div>
</div>
<% end %>
</div>
so i got an error undefined method `each' for nil:NilClass
any ideas

in your partial, you use #movies but in the controller, you are calling it #category_movies - you will need to use the same variable name, or use local variables.
eg with local variables:
<%= render 'movies/movies', :movies => #category_movies %>
# and in the partial
<% movies.each do |movie|%>
Note: not tested for bugs and typos...

Instance variable #category_movies must be the same in the controller and in the views :)
#movies is not declared so it's nil !

Related

Strange Things - Ruby on Rails 5

Hey guys I'm trying to catch all my categories descriptions inside my Category model and show them at my shop index page. So far everything working fine. All categories came perfectly at screen but just below then rails shows all categories as an array.
This is my Category controller
class Site::HomeController < ApplicationController
def index
#categories = Category.all
end
end
This is my index page
`
<div class="row">
<div class="col-lg-3">
<h1 class="my-4">Shop Name</h1>
<div class="list-group">
<%= #categories.each do |cat| %>
<%= cat.description %>
<% end %>
</div>
</div>`
and below you can check the issue
I appreciate for some help.
regards
Try this:
<% #categories.each do |cat| %> #remove "="
<%= cat.description %>
<% end %>

Rails retrieving all records in show controller

In my rails category show controller for categories I have it setup like this
def show
#categories = Category.find_by(params[:name])
end
But when I visit this controller it returns all records of products found in the category instead of single category.
Here is the code in my view controller for category
<div class="grid">
<% #categories.products.each do |product| %>
<%= link_to product_path(id: product.slug, category_name: product.category.name), class: "card" do %>
<div class="product-image">
<%= image_tag product.productpic.url if product.productpic? %>
</div>
<div class="product-text">
<h2 class="product-title"> <%= product.name %></h2>
<h3 class="product-price">£<%= product.price %></h3>
</div>
<% end %>
<% end %>
</div>
What am i doing wrong here?
First of all, for security purposes, you should never trust the params hash to retrieve records. Rails will "make the data safe" if you use a hash as your arguments. Use this code below:
def show
#category = Category.find_by(name: params[:name])
end
Second, usually on a show page, you only want to retrieve one record and therefore the variable should be named as singular. I corrected that above.
Third, it helps if you use proper indenting when posting examples. It makes it easier for us to help you.
Fourth, the line below (I changed #categories to #category) is basically saying: "Now that I have this single category, find all the products associated with it in the products table and put them into the |product| variable for iteration"
<% #category.products.each do |product| %>
I'm not sure what you want to do with the category, but if you keep this line of code, it will always show you all the products. Maybe you only want to show the most recent 3, in which case you could do something like this:
In your controller:
def show
#category = Category.find_by(name: params[:name])
#recent_products = #category.products.order(created_at: :desc).limit(3)
end
In your view:
<div class="grid">
<% #recent_products.each do |product| %>
<%= link_to product_path(id: product.slug, category_name: product.category.name), class: "card" do %>
<div class="product-image">
<%= image_tag product.productpic.url if product.productpic? %>
</div>
<div class="product-text">
<h2 class="product-title"> <%= product.name %></h2>
<h3 class="product-price">£<%= product.price %></h3>
</div>
<% end %>
<% end %>
</div>
You can do this way
in your controller you can write this code
def show
#category = Category.find_by_name(params[:name])
end
and in your view it will work
<div class="grid">
<% #category.products.each do |product|%>
// place your code what you want to display
<% end %>
</div>
I hope it would help you and still if you have any concern please let me know.

Call a method associated with partial rails

In my controller I have this method that retuns to me the list of specific books controller/books_controller
def postings
#books = Book.postings(current_user.id).order("created_at ASC")
render :partial =>'postings'
end
I have a partial in views/books/_postings.html.erb
<div class="container">
<h4>My Partial Postings</h4>
<% #books.each do |book| %>
<div class="row">
<div class="col-sm-2"><img src="<%= book.image_path %>" alt="..." class="img-responsive"/></div>
<div class="col-sm-10">
<h4 class="nomargin"><%= book.title %></h4>
<p><%= book.description %></p>
<p>Quantity: <%= book.quantity %></p>
<p>Available for: <%= book.sale_type %></p>
</div>
</div>
<hr>
<% end %>
</div>
In my routes :
resources :books do
collection do
get 'postings'
end
end
on running rake routes :
postings_books GET /books/postings(.:format) books#postings
When I use localhost:3000/books/postings I get the desired partial showing list of books .But when I want to call this partial from some other view eg from localhost:3000/dashboard/index:
<div class="tab-pane" id="postings">
<%= render 'books/postings', :collection => #books %>
</div>
I get the following error:
Showing /home/swati/867/WorkSpace2/assignment_3/app/views/books/_postings.html.erb where line #4 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #4):
<div class="container">
<h4>My Partial Postings</h4>
<% #books.each do |book| %>
<div class="row">
<div class="col-sm-2"><img src="<%= book.image_path %>" alt="..." class="img-responsive"/></div>
<div class="col-sm-10">
I understand that render is just rendering the partial without calling my method postings in books_controller and my partial has no access to #books , which is nil. How can aprroach this ?
When you access dashboard/index you are actually calling index method of dashboards_controller. If you would like to render the books/postings partial there, you need to add the list of books (#books) in that controller too.
More info here: http://guides.rubyonrails.org/action_controller_overview.html

Display products from ShopSense API

How do I display products from the ShopSense API in Rails using shopsense-ruby?
JSON.parse(response)["products"] is returning nil:
NoMethodError in Main#index
Showing /home/dev/demo-shopsense/app/views/shared/_shopsense.html.erb where line #3 raised:
undefined method `any?' for nil:NilClass
Extracted source (around line #2):
<div class="custom_widget">
<% if #products.any %>
<% #products.each do |product| %>
<div class="product">
<%= image_tag product['image']['url'] %>
<p><%= product['name'] %></p>
main_controller.rb:
class MainController < ApplicationController
def index
client = Shopsense::API.new('partner_id' => 'uid0000-0000000-00')
response = client.get_looks("New")
#products = JSON.parse(response)["products"]
end
end
shared/_shopsense.html.erb:
<div class="custom_widget">
<% if #products.any? %>
<% #products.each do |product| %>
<div class="product">
<%= image_tag product['image']['url'] %>
<p><%= product['name'] %></p>
</div>
<% end %>
<% end %>
</div>
I've set up a simple demo app demo-shopsense that should be easy to get up and running.
The parsed response of your request looks like this:
{"totalCount"=>"536121",
"looks"=>
[{"id"=>"12328367",
"title"=>"black",
...
As you can see instead of 'products' we have 'looks'.
#products = JSON.parse(response)["looks"]
When you are working with external services, it's very important to find out the exact format of the response.
EDIT:
I think in this case you actually need to use 'search' method on the client instead of 'get_looks', if you want to get products.

Can't link to objects belonging to a category

I have a method that groups all my book categories together
def self.categories_list
joins(:books).
select('categories.id, categories.name, count(*) AS books_count').
group('categories.id, categories.name').
order('books_count DESC')
end
I can then output them to my view like so
#bookcategories = Category.categories_list
What I want to do then is link to all the books belonging to say 'Computing' by clicking 'Computing' in the view
<% #bookcategories.each do |b| %>
<li><%= link_to b.name, category_path(b.name) %></li>
<% end %>
This should take me to my show action of my category controller
def show
#category = Category.where(:name => params[:name]).first
#categorisedbooks = #category.books #get me all books that have the category name
end
and the view for the show action
<div class="container">
<div class="row ">
<div class="span12">
<% #categorisedbooks.each do |c| %>
<%= image_tag c.avatar.url(:medium), :class=> "allBooksCover" %>
<% end %>
</div>
</div>
</div>
So when I click 'Computing' for example I get
undefined method `books' for nil:NilClass
and the params are being passed as
Parameters:{"id"=>"Computing"}
So, you need in your show action
#category = Category.where(:name => params[:id]).first
# etc

Resources