Recurring Action template error ruby on rails - ruby-on-rails

I keep on having this error
ActionView::Template::Error (undefined method `each' for nil:NilClass):
Here's my show.html.erb
<% #bookings.each do |booking| %>
<% if booking.checkin_on > Date.today %>
<% if booking.status == "Confirmed" %>
<li class="dashboard">
<%= cl_image_tag(booking.bed.photo.path, width: 400, height: 300, crop: :fill, class: "pdt-image hidden-xs" ) %>
<div class='product-body'>
<h2><%= booking.bed.title %></h2>
<p>City: <strong><%= booking.bed.city %></strong></p>
<p>Address: <strong><%= booking.bed.address %></strong></p>
<p>Total price: <strong><%= booking.value %> €</strong></p>
</div>
<div>
<ul class="list-unstyled hidden-sm hidden-xs padded">
<li><strong>Your booking is confirmed !</strong></li>
<li class="text-right"><%= link_to "Delete this booking", booking_path(booking), method: :delete, class:"btn btn-default", data: {confirm: "Are you sure"} %> </li>
</ul>
</div>
</li>
<% end %>
<% if booking.status == "Canceled" %>
<li class="dashboard">
<%= cl_image_tag(booking.bed.photo.path, width: 400, height: 300, crop: :fill, class: "pdt-image hidden-xs" ) %>
<div class='product-body'>
<h2><%= booking.bed.title %></h2>
<p>City: <strong><%= booking.bed.city %></strong></p>
<p>Address: <strong><%= booking.bed.address %></strong></p>
<p>Total price: <strong><%= booking.value %> €</strong></p>
</div>
<div>
<ul class="list-unstyled hidden-sm hidden-xs padded">
<li><p><%= booking.bed.user.first_name%> canceled your booking </p></li>
</ul>
</div>
</li>
<% end %>
<% end %>
<% end %>
And here's my my_bookings controller
class My::BookingsController < ApplicationController
def index
#bookings = Booking.where(user_id: current_user.id)
#bookings = Booking.all
#beds = Bed.all
end
def show
set_booking
#bed = #booking.bed
end
private
def set_booking
#booking = Booking.find(params[:id])
end
end
Any suggestions? Or anything I can't see? I have tried almost everything I can think of at the moment. Thanks!

You are not declairing the #bookings variable on your show method, which explains the crash. It appears you are declaring it as you wanted it on the first line of your index method. Just change where you declare it, and it shall be alright.
Also, to avoid further headaches, you should refactor the set_booking method to:
def set_booking
#booking = Booking.find_by(id: params[:id])
end
by deafult .find() will crash your view if it doesn't find anything
.find_by, on the other hand, will return an empty answer, so it won't crash. Also, it's more versatile, since this way you can search from innumerous other variables set in your model, i.e. name.

By convention in Rails controller actions (index and show in your case) render views with same names, in your case those might be intex.html.erb and show.html.erb. In your show method you define two variables: #bed and #booking and in your view (show.html.erb) you try to loop variable #bookings which you have not defined in your controller action. Thus, you are getting this error.
Looks like you need to rename show.html.erb to index.html.erb as you are listing bookings and their information in it.

Related

undefined method 'each' when accessing articles from navbar in rails app

I need to be able to access articles through the navbar dropdown.
in my views/application/_navbar.html.erbI have the code snipped below. It is not working and I always get this error undefined method 'each' for nil:NilClass
when I hit the link in the dropdown the app goes to the right path http://localhost:3000/lcas/1
I only need to be able to access the first article in each category so http://localhost:3000/lcas/1 is the right path for the first link in the dropdown
code from views/application/_navbar.html.erb
<ul class="dropdown-menu">
<% #lcas.each do |lca| %>
<li><%= link_to lca.title, lca_path(lca) %></li>
<% end %>
<% #energy_analyses.each do |energy_analysis| %>
<li><%=link_to energy_analysis.title, energy_analysis_path(energy_analysis) %></li>
<% end %>
<% #green_accountings.each do |green_accounting| %>
<li><%= link_to green_accounting.title, green_accounting_path(green_accounting) %></li>
<% end %>
<li class="divider"></li>
<li>Something</li>
<li class="divider"></li>
<li>something</li>
</ul>
On my index.html.erbI have basically the same code and there it works.
<% #lcas.each do |lca| %>
<div class="col-md-4 col-xs-12">
<span class="glyphicon glyphicon-tasks icons" aria-hidden="true"> </span>
<div class="panel-heading">
<h3 class="panel-title"><%= link_to lca.title, lca_path(lca) %></h3>
</div>
</div>
<% end %>
I've tried to add
#lcas = Lca.all
#energy_analyses = EnergyAnalysis.all
#green_accountings = GreenAccounting.all
to the application_controller.rb but with out any success.
here is the lcas_controller.rb
class LcasController < InheritedResources::Base
private
def lca_params
params.require(:lca).permit(:title, :body, :image)
end
end
It would be very nice if someone could guide me through this.
You probably need few things:
Set a before_action method for those variables in application_controller.rb to make sure each other controller calls it and pass the variable to their corresponding view:
before_action :set_vars
def set_vars
#lcas = Lca.all
#energy_analyses = EnergyAnalysis.all
#green_accountings = GreenAccounting.all
end
Now you should be able to access #lcas from your partial, but using instance variables in partials is violating MVC, so you should pass locals to it:
<%= render 'application/navbar', :lcas => #lcas %>
Not sure how to pass multiple locals, maybe like this:
<%= render 'shared/navbar', locals: {:lcas => #lcas, :energy => #energy_analyses, :green => #green_accountings} %>
And of course, don't use # in partial if passing locals:
<% energy.each do |energy_analysis| %>

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.

How do I print validation messages for form_for :post structure?

I have something like
<div class="userInput">
<%= form_for :scribble do |f| %>
<%= f.text_area :scribble, cols: 65, rows: 4,:maxlength => 255%>
<%= f.submit %>
<% end %>
</div>
1)My Scribble model has min and max character length validation, now how do I print the error messages here. If it is an instance variable I know how to print, but this is a symbol.
2) This code is present in the application.html.erb. I am not able to understand how do I move it into a view of Scribble controller other than appliation. Problem is this form is not independent, it is a part of action index display of controller Scribbles,(and the form should be displayed always) and action index is already doing listing of scribbles.
Controller
def index
#scribbles = Scribble.order("scribbles.scribble DESC").all
end
def show
end
def new
end
def create
#scribble = Scribble.new(profile_params)
#scribble.likes =#scribble.dislikes =#scribble.shares=0;
#scribble.save
#scribbles = Scribble.order("scribbles.scribble DESC").all
render :index
end
Here how i out-put any errors or validation messages:
Controller:
def create
#scribble = Scribble.new(profile_params)
#scribble.likes =#scribble.dislikes =#scribble.shares=0;
if #scribble.save
flash[:notice] = "Scribble is successfully created"
redirect_to root_url
else #
render 'index'
end
end
Views:
Create a partial to show error messages if any e.g _error_messages.html.erb
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert callout text-center" data-closable>
<p><strong>This form contains <%= pluralize(object.errors.count, 'error') %>.</strong></p>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<button class="close-button" aria-label="Dismiss alert" type="button" data-close>
<span aria-hidden="true">×</span>
</button>
</div>
</div>
<% end %>
Render errors:
Now you can call <%= render 'layouts/error_messages', object: #scribble %> and put it anywhere in your views to render the errors validation. note: the object is passed, so it can be re-use to any form. credits to Hartl Tutorial.

Need to group shows by day in a rails Application

I am trying to get shows on a certain day to show up just for that day and I would like to be able to see what shows are going on in the next couple of days as well.
The View:
<% t = Time.new %>
<h2 class="center" style="color:#2A2C2B"><u><%= t.strftime("%A, %B %e") %></u></h2>
<% #clubs.each do |club| %>
<!-- # <% club.shows.future.present? %> -->
<h1 class="club"><%= link_to club.name, club.website %> </h1>
<% club.shows.future.each do |show| %>
<h3 class="center"><%= show.pretty_start_time %></h3>
<% show.comedians.each do |comedian| %>
<div>
<ol>
<h4 class="comedian"><%= link_to simple_format(comedian.name),comedian_path(comedian) %></h4>
<p class="bio"><u><%= comedian.bio %></u></p>
</ol>
</div>
<% end %>
<% end %>
<%- end -%>
The Comedy Hub Controller:
class ComedyHubsController < ApplicationController
def show
#clubs = ComedyClub.all
end
end
This might work:
<% shows.goup_by{|show| show.date}.each do |dategroup| %>
<# do something to indicated the group up here? %>
<%= dategroup.each do |show| %>
<li> <%# put details here %> </li>
<% end %>
<% end %>
Assuming, there is a DateTime column on Show called start and the ComedyClub model has a a has_many :shows and the Show model has the belongs_to :comedy_club association defined
In your ComedayHubsController#show method, do the following query
#clubs = ComedyClub.join(:shows).where("shows.start >=?", DateTime.now).order("shows.start ASC")
Now only clubs with shows in the future will be sent to the view and already ordered by start.

Refactoring acts_as_taggable suggestions?

I have an application with a list of majors and each one is tagged with categories using the acts-as-taggable-on gem. I have a page where you can explore majors by category. So, you see the categories and grouped under the category is a list of the majors.
My categories_controller.rb file:
def index
#creative = Major.tagged_with("creative arts")
#engineering = Major.tagged_with("engineering and technology")
#mechanics = Major.tagged_with("mechanics and construction")
#transportation = Major.tagged_with("transportation")
#science = Major.tagged_with("science")
#math = Major.tagged_with("math")
#resources = Major.tagged_with("natural resources")
#healthcare = Major.tagged_with("health care")
#social_sciences = Major.tagged_with("social sciences")
#education = Major.tagged_with("education")
#law = Major.tagged_with("law")
#management = Major.tagged_with("management and marketing")
#administrative = Major.tagged_with("administrative and clerical")
#services = Major.tagged_with("services")
#tags = Major.tag_counts
end
You can see the duplication. This is compounded on the view template.
Here's part of the index.html.erb page:
<!-- Creative Arts -->
<h2 class="major-categories-landing">Creative Arts</h2>
<% #creative.sample(10).each do |creative| %>
<%= link_to creative, class: 'span2 category-landing' do %>
<%= image_tag creative.image(:similar), class: 'img-polaroid', id: 'category-landing-list' %>
<p class="category-landing-list-name"><%= creative.name %></p>
<% end %>
<% end %>
<%= link_to "View all #{#creative.count} majors in this category.", category_path("creative arts"), class: "view-category-show-page" %>
<!-- Social Sciences -->
<h2 class="major-categories-landing">Social Sciences</h2>
<% #social_sciences.sample(10).each do |ss| %>
<%= link_to ss, class: 'span2 category-landing' do %>
<%= image_tag ss.image(:similar), class: 'img-polaroid', id: 'category-landing-list' %>
<p class="category-landing-list-name"><%= ss.name %></p>
<% end %>
<% end %>
<%= link_to "View all #{#social_sciences.count} majors in this category.", category_path("social sciences"), class: "view-category-show-page" %>
and so on for each category. I have tried #category = Major.tagged_with(params[:tag]) and many variations to that to no avail. This is my first time working with acts_as_taggable_on and although I've read the documentation over and over I can't quite figure this out.
I hope to extend this out throughout the application and so I want to figure it out now before I get a lot duplicate code. Thanks for sharing any ideas or suggestions!!
I am running a rails 3.2.11 app.
UPDATE
Here's how much better this is now:
My categories_controller.rb file:
def index
#major_categories = ["creative arts", "social sciences", "science", ....]
end
My index.html.erb page:
<% #major_categories.each do |c| %>
<!-- Title and blue strip -->
<div class="category-strip">
<div class="container">
<h2 class="major-categories-landing"><%= c %></h2>
</div>
</div>
<!-- Show Each Major in this Category -->
<div class="container">
<div class="row-fluid">
<% Major.tagged_with(c).order('RANDOM()').limit(10).each do |major| %>
<%= link_to major, class: 'span2 category-landing' do %>
<%= image_tag major.image(:similar), class: 'img-polaroid' %>
<p class="category-landing-list-name"><%= major.name %></p>
<% end %>
<% end %>
</div>
<!-- Link to View All Majors -->
<div class="row-fluid">
<div class="view-all-category">
<%= link_to "View all #{Major.tagged_with(c).count} majors in this category.", category_path(c), class: "view-category-show-page" %>
</div>
</div>
</div>
<% end %>
I would do something like this:
# in categories_controller.rb
def index
#categories = ["creative arts", "engineering and technology",
"mechanics and construction", ...]
end
# in index.html.erb
<%= render partial: "category", collection: #categories %>
# in _category.html.erb
<h2 class="major-categories-landing"><%= category.titleize %></h2>
<% Major.tagged_with(category).order('rand()').limit(10).each do |major| %>
<%= link_to major, class: 'span2 category-landing' do %>
<%= image_tag major.image(:similar), class: 'img-polaroid',
id: 'category-landing-list' %>
<p class="category-landing-list-name"><%= major.name %></p>
<% end %>
<% end %>
<%= link_to "View all #{Major.tagged_with(category).count} majors in this category.",
category_path(category), class: "view-category-show-page" %>
Btw: The link to each major is invalid html. A link (because a it is an inline element) should not contain a paragraph (because p is a box element). Furthermore each link for each category would have the same id, but ids must be unique in each html document.

Resources