undefined method `each' do Subject - ruby-on-rails

I am getting the following undefined method each error.
I am following along with the exercises on Lynda and I am stuck here. I have attempted to understand the solutions in the other questions but its still beyond my understanding. any help will be greatly appreciated.
ActionView::Template::Error (undefined method `each' for nil:NilClass):
10: <th>Pages</th>
11: <th>Actions</th>
12: </tr>
13: <% #Subjects.each do|subject| %>
14: <tr>
15: <td><%= subject.position %></td>
16: <td><%= subject.name %></td>
app/views/subjects/index.html.erb:13:in `_app_views_subjects_index_html_erb__3548269486732453408_70351994996820'
Here is the index code that is defined in models/views/subjects/index.html.erb
<div class = "subjects index">
<h2>Subjects</h2>
<%= link_to("Add New Subject",'#', :class => 'action new') %>
<table class ="listing" summary ="Subject list">
<tr class = "header">
<th> </th>
<th>Subject</th>
<th>Visible</th>
<th>Pages</th>
<th>Actions</th>
</tr>
<% #Subjects.each do|subject| %>
<tr>
<td><%= subject.position %></td>
<td><%= subject.name %></td>
<td class ="center"><%= subject.visible ? 'Yes' : 'No' %></td>
<td class = "center"><%= subject.pages.size %></td>
<td class = "action">
<%= link_to("Show", '#',:class => 'action show') %>
<%= link_to("Edit", '#' ,:class => 'action edit') %>
<%= link_to("Delete", '#',:class => 'action delete') %>
</td>
</tr>
<% end %>
</table>
</div>
Subject model is as follows:
class Subject < ActiveRecord::Base
has_many :pages
scope :visible, lambda { where(:visible => true) }
scope :invisible, lambda { where(:visible => false) }
scope :sorted, lambda { order("subjects.position ASC") }
scope :newest_first, lambda { order("subjects.created_at DESC")}
scope :search, lambda {|query|
where(["name LIKE ?", "%#{query}%"])
}
end
when i type Subject.all
irb(main):001:0> Subject.all
Subject Load (0.2ms) SELECT `subjects`.* FROM `subjects`
=> #<ActiveRecord::Relation [#<Subject id: 1, name: "Initial Subject", position: 1, visible: true, created_at: "2015-04-28 04:11:54", updated_at: "2015-04-28 04:18:58">, #<Subject id: 2, name: "Revised Subject", position: 2, visible: true, created_at: "2015-04-28 04:15:01", updated_at: "2015-04-28 04:22:12">, #<Subject id: 4, name: "Third Subject", position: 3, visible: false, created_at: "2015-04-28 04:31:04", updated_at: "2015-04-28 04:31:04">]>

Your #Subjects is uppercase so this is empty. Also please check first #subjects.present? before loop through each.

Related

Issues in getting UI in proper format using ruby on rails

I am working on a Ruby on rails project. I want to get this UI format:
I tried the below code, but not getting proper results. User can create controller dynamically from permission so the controller can be anything (User,Role,Permission etc)
Controller
def display
param = params[:role]
id=param[:id]
#permission = Role
.joins(:permissions)
.where('roles.id=?',id)
.select('permissions.*')
end
result of #permission
[#<Role id: 4, name: "index", controller: "User", created_at: "2018-08-21
06:29:47", updated_at: "2018-08-24 06:39:37">,
#<Role id: 16, name: "create", controller: : "User", created_at: "2018-08-24
07:11:08", updated_at: "2018-08-24 07:11:08">,
#<Role id: 21, name: "destroy", controller: : "User", created_at: "2018-08-
24 07:31:17", updated_at: "2018-08-24 07:31:17">,
#<Role id: 25, name: "update", controller: : "User", created_at: "2018-08-24
07:52:00", updated_at: "2018-08-24 07:52:00">,
#<Role id: 26, name: "edit", controller: : "Role", created_at: "2018-08-27
06:38:39", updated_at: "2018-08-27 06:38:39">]>
view
<%= link_to 'Create', new_permission_path %>
<br/>
<thead>
<tr>
<th width="25px"><%= "User" %></th>
</tr>
<tr>
<% #permission.each do |p| %>
<% if (p.controller== 'User') %>
<th width="25px"> <%= check_box_tag "p[]", p.id %> <%= p.name %></th>
<% end %>
<% end %>
</tr>
</thead>
I think your structure should be like below
role model
class Role < ApplicationRecord
has_many :role_permissions
has_many :permissions, through: :role_permissions, dependent: :destroy
end
permission model
class Permission < ApplicationRecord
has_many :role_permissions
has_many :roles, through: :role_permissions, dependent: :destroy
end
and the middle table between role and permissions
class RolePermission < ApplicationRecord
belongs_to :role
belongs_to :permission
end
Create data from seeds.rb
Role.create!(name: admin)
Permission.create!([
{subject_class: 'Users', action: 'create',name: 'Create a User',description: 'nil', title: "Users"},
{subject_class: 'Users', action: 'index',name: 'List users',description: 'nil', title: "Users"},
{subject_class: 'Users', action: 'update',name: 'Update User',description: 'nil', title: "Users"},
{subject_class: 'Users', action: 'destroy',name: 'Remove User',description: 'nil', title: "Users"},
{subject_class: 'Users', action: 'show',name: 'Show User',description: 'nil', title: "Users"},
Role.first << Permission.all
Subject Class is name of controller and action will be name of action.
In the view you can load all role and permissions like below, I used accordion in my view, so you might need to update view as per your need
<% roles = Role.includes(:permissions).all %>
<% uniq_controller = Permission.all.group_by { |p| p.title } %>
<div class="accordion panel-group" id="accordion2">
<% uniq_controller.each do |permission| %>
<div class="panel panel-default">
<%= link_to "##{permission.first}" ,data: {parent: "#accordion2", toggle: "collapse"} do %>
<div class="panel-heading">
<h3 class="panel-title">
<%= permission.first.gsub("_"," ") %>
</h3>
</div>
<% end %>
<div id="<%= permission.first %>" class="panel-collapse collapse">
<div class="collapse show" role="tabpanel" aria-labelledby="headingOne">
<div class="card-block">
<table>
<% permission.second.each do |cont| %>
<tr>
<td><%= cont.name %></td>
<td>
<%= f.check_box :permission_ids, {multiple: true}, cont.id, nil %></td>
</tr>
<% end %>
</table>
</div>
</div>
</div>
</div>
<% end %>
</div>
In the controller just add the permission_ids: [] in permit parameters

Sortable table columns based on hash & key array

I would like to create sortable columns for my table which tabulates data based on hashes. By following http://railscasts.com/episodes/228-sortable-table-columns?view=asciicast. From what I understand, order method would only work sorting out a Model. What's the best way of sorting out columns for such tables. I have 29 similar tables as mentioned. My codes are as below :-
admins_controller.rb
class AdminsController < ApplicationController
array =[]
User.each do |user|
company_name = Company.find(user.company_id).name
array.push(company_name)
end
company = array.inject(Hash.new(0)) { |h, e| h[e] += 1 ; h }
end
Results of the above the above query would look like this :-
array = [["3M", 4], ["A.P. Møller-Mærsk Group", 10], ["ABB", 14], ["Abbott Laboratories", 12]]
On views :-
admins.html.erb
<table class="table">
<tr>
<th><%= link_to "Company", remote: true, :sort => "hash" %></th>
<th><%= link_to "Value", remote: true, :sort => "key" %></th>
<th><%= link_to "Percentage", remote: true, :sort => "Percentage" %></th>
</tr>
<% if #mentors.try(:any?) %>
<% #mentors.each do |key, value| %>
<tr>
<td><%= key %></td>
<td><%= value %> </td>
<td><%= ((value.to_f/#total_co.to_f).to_f * 100 ).round(2)%> </td>
</tr>
<% end %>
<% else %>
<td> nil </td>
<td> nil </td>
<td> nil </td>
<% end %>
</table>
You could go for a JavaScript / jQuery solution like http://tablesorter.com/docs/
This would allow for sorting in frontend and you would not need to adjust the backend.
If you want to have a backend solution, you could go for sorting by column index. A simple solution would be something like this:
Controller:
class AdminsController < ApplicationController
def index
array =[]
User.each do |user|
company_name = Company.find(user.company_id).name
array.push(company_name)
end
company = array.inject(Hash.new(0)) { |h, e| h[e] += 1 ; h }
sort_column = params.fetch(:sort, 0).to_i
company.sort! { |a, b| a[sort_column] <=> b[sort_column] }
end
end
View:
<table class="table">
<tr>
<th><%= link_to "Company", remote: true, :sort => 0 %></th>
<th><%= link_to "Value", remote: true, :sort => 1 %></th>
<th><%= link_to "Percentage", remote: true, :sort => 1 %></th>
</tr>
<% if #mentors.try(:any?) %>
<% #mentors.each do |key, value| %>
<tr>
<td><%= key %></td>
<td><%= value %> </td>
<td><%= ((value.to_f/#total_co.to_f).to_f * 100 ).round(2)%> </td>
</tr>
<% end %>
<% else %>
<td> nil </td>
<td> nil </td>
<td> nil </td>
<% end %>
</table>
For reverting sort order, you would need to also pass a direction state and probably reverse order.

Configure Sunspot Solr search with scope

Controller
class GearsController < ApplicationController
before_action :set_gear, only: [:show, :edit, :update, :destroy]
def primary
#gears = Gear.search do
with(:Lab, 'Primary')
order_by(:RU, :desc)
end
end
Model
class Gear < ActiveRecord::Base
validates_uniqueness_of :Nic1mac, :Nic2mac, :Nic3mac, :IBmac, :SN, :allow_blank => true
attr_readonly :Devtype, :Nic1mac, :Nic2mac, :Nic3mac, :IBmac, :SN
scope :Mini, -> { where(lab: 'Mini') }
scope :Primary, -> { where(lab: 'Primary') }
scope :Support, -> { where(lab: 'Support') }
scope :M5, -> { where(lab: 'M5') }
scope :P5, -> { where(lab: 'P5') }
searchable do
integer :RU
text :Devname
text :Devtype
string :Lab
text :Swportib
text :Swport1
text :Swport2
text :Swport3
text :IBip
text :Nic1
text :Nic2
text :Nic3
text :Nic1mac
text :Nic2mac
text :Nic3mac
text :IBmac
text :Psu1
text :Psu2
text :SN
end
end
View
<% provide(:title, "SP4 Primary") %>
<p id="notice"><%= notice %></p>
<h1>SP4 Primary</h1>
<%= form_tag gears_path, :method => :get do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<head>
<style>
table, th, td { border: 1px solid black;}
th, td { padding: 15px;}
</style>
</head>
<table>
<thead>
<tr>
<th>RU</th>
<th>Dev Name</th>
<th>Dev Type</th>
<th>Lab</th>
<th>SW PortIB</th>
<th>SW Port1</th>
<th>SW Port2</th>
<th>SW Port3</th>
<th>IB IP</th>
<th>NIC1</th>
<th>NIC2</th>
<th>NIC3</th>
<th>NIC1 Mac</th>
<th>NIC2 Mac</th>
<th>NIC3 Mac</th>
<th>IB Mac</th>
<th>PSU1</th>
<th>PSU2</th>
<th>SN</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #gears.each do |gear| %>
<tr>
<td><%= gear.RU %></td>
<td><%= gear.Devname %></td>
<td><%= gear.Devtype %></td>
<td><%= gear.Lab %></td>
<td><%= gear.Swportib %></td>
<td><%= gear.Swport1 %></td>
<td><%= gear.Swport2 %></td>
<td><%= gear.Swport3 %></td>
<td><%= gear.IBip %></td>
<td><%= gear.Nic1 %></td>
<td><%= gear.Nic2 %></td>
<td><%= gear.Nic3 %></td>
<td><%= gear.Nic1mac %></td>
<td><%= gear.Nic2mac %></td>
<td><%= gear.Nic3mac %></td>
<td><%= gear.IBmac %></td>
<td><%= gear.Psu1 %></td>
<td><%= gear.Psu2 %></td>
<td><%= gear.SN %></td>
<td><%= link_to 'Show', gear %></td>
<td><%= link_to 'Edit', edit_gear_path(gear) %></td>
<td><%= link_to 'Destroy', gear, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
Above is my Controller and Model code. I am trying to set up the search so it only searches through records within the scope specified. Currently it will return all results and does not pay attention to the scope. I believe I am close to making it work but just don't have the right syntax. Then again I may be wrong, thus any help suggestions or different ways of doing this are welcome.
You can add a code like this in your search method
with(:lab, 'Support')
and in your model add this
string :lab
The solution was adding without in my gears_controller.rb file.
gears_controller.rb
def rack1
#gears = Gear.where("Lab like ? OR Lab like ? OR Lab like ?", "%Primary%", "%Mini%", "%Support%")
#search = Gear.search do
fulltext params[:search]
without(:Lab, "P5")
without(:Lab, "M5")
order_by(:RU, :desc)
end
#gears = #search.results
end
Adding the without fields allowed me to only search through the records with the specific Lab values that were specified in my #gears variable.

Can not access collection object's value in erb file - has_many relationship - ruby on rails

In my application, there are two classes , which have 'has_many' relationship.
And from that design, I can fetch object from my controller(*_controler.rb) and can pass successfully to my view (*.html.erb)
But on view part(*.html.erb) i can not access object's collection class...
I got following exception:
ActionView::TemplateError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.inject) on line #31 of app/views/student/_populate.html.erb:
Model Classes:
class Student < ActiveRecord::Base
has_many :Subject, :class_name=>"Subject"
attr_accessible :first_name, :middle_name, :last_name,
self.table_name="students"
set_primary_key :id
blahblah
end
class Subject < ActiveRecord::Base
belongs_to :Student, :foreign_key=>'student_id'
attr_accessible :student_id, :name
self.table_name="subjects"
blahblah
end
Controller:
class StudentController < ApplicationController
require "student.rb"
def populate
#pos=0
filter_query = ''
if !params[:firstName].blank?
filter_query +=" first_name='" + params[:firstName].to_s + "' and"
end
if filter_query !=''
filter_query= filter_query[0..filter_query.length-4]
#stuData= Student.find(:all, :conditions=>filter_query)
end
end
View:
populate.html.erb
<div class="header">
<div class="heading" style="float:left;width:900px;">
<% form_tag(:controller=>"student", :action=>"populate") do %>
<table>
<tr>
<td width="10"> <label> First Name:</label> </td>
<td width="40"> <%= text_field_tag('firstName') %> </td>
</tr>
</table>
<input name="submitFormName" class="form_submit" type="submit" value="Search" />
<% end %>
<div height="10"> </div>
</div>
</div>
<div class="students" style="float:left;width:1330px;">
<% if !#stuData.blank? %>
size = <%= #stuData.size %>
<% if !#stuData.nil? %>
<%= render :partial=>'populate' , :locals=>{:stuData => #stuData} %>
<% end %>
<% else %>
<div>Not found...</div>
<% end %>
</div>
_populate.html.erb
<div style="overflow-y:auto;overflow-x:scroll;">
<table >
<thead>
<th>Id</th>
<th>First Name</th>
<th>Middle Name </th>
<th>Last Name</th>
<th>Subject Name</th>
</thead>
<% stuData.each do |item| %>
<tr>
<td id="studentId"> <%= item.id %> </td>
<td id="firstNameId"> <%= item.promotion_code %> </td>
<td id="middleNameId"> </td>
<td id="lastNameId"> </td>
<td id="cityId">
<% #var1 = item.Subject %>
<% if #var1.nil? %>
<% #var1.each do |pc| %>
<%= pc.name %>
<% end %>
<% end %>
</td>
</tr>
<% end %>
</table>
</div>
I have crossed check on console:
#student = Student.find(144)
=> #<Student id: 4, first_name: "ABC", middle_name: "DEF", last_name: "GHI">
>>
?> #isNullCheck = #student.Subject.nil?
=> false
>>
?> #subList = #student.Subject
=> [#<Subject id: 5, student_id: 4, name: "Maths">, #<Subject id: 6, student_id: 4, name: "English"> ]
>>
?> #StuSub1 = #student.Subject[0]
=> #<Subject id: 5, student_id: 4, name: "Maths">
>>
?> #StuSub2 = #student.Subject[1]
=> #<Subject id: 6, student_id: 4, name: "English">
==
?> #StuSub3 = #student.Subject[2]
=> nil
>>
>> #StuSubValue1 = #student.Subject[0].value
=> Maths
>>
>> #StuSubValue2 = #student.Subject[0].value
=> English
>>
Problem:
When i will search any student details from the page(populate.html.erb), my controller will fetch the data and passed the object (#stuData) to the template(_populate.html.erb).
Template(_populate.html.erb) can print student's data.
But can not print student's subject's name. (As student has many subjects)
I have googled many things....
i think there is nothing wrong in model's design and controller part....
but i think problem might be with
page rendering or
local parameters passing to template or
collection parameter passing to template...
but i am not sure....
can any one help me in this???
Thanks in advance,
Your relationships are set up incorrectly. Variable names cannot begin with a capital letter. This article may help.
Set them up without using capitals and use plurals instead - like so:
has_many :subjects and belongs_to :student
and make sure you propagate changes through your views

Setting a params hash to a variable within the controller (rails)

I'm very new to rails and have this fairly basic question:
I have a form that takes in an array:
<td><%= fields_for "days" do |form| %>
M: <%= form.check_box "", {}, 'M', '' %>
T: <%= form.check_box "", {}, 'T', '' %>
W: <%= form.check_box "", {}, 'W', '' %>
Th: <%= form.check_box "", {}, 'Th', '' %>
F: <%= form.check_box "", {}, 'F', '' %>
<% end %>
This should be accessible through params[:days]. How can I assign params[:days] to a variable within the controller? #days is not correct here, right? (There's no Days object, so there's no instance of that object). What should go in the [correct_variable] slot below?
[correct_variable] = params[:days]
Thanks!
In response to comments:
I tried using #days, but for some reason it wouldn't get called where I'd like it to. In particular, I'd like to pass it to my Search model:
class Search < ActiveRecord::Base
attr_accessible :name, :day, :units, :instructor
def courses
#courses ||= find_courses
end
private
def find_courses
Course.find(:all, :conditions => conditions)
end
def day_conditions
["courses.day LIKE ?", "%"+ #days.join("%")+"%"]
end
I first instantiate #days in my courses controller (which is connected, through the index method, to a partial that uses an instance of the Search object.
More code:
From courses/index.html.erb:
<% if #search.save %>
<div id = "results_scroll">
<%= render :partial => 'searches/search_results' %>
</div>
<% else %>
From search_results partial:
<% "Search" %>
<table>
<tr>
<th align="left" width="25%"><%= 'Name' %></th>
<th align="left" width="10%"><%= 'Number' %></th>
<th align="left" width="20%"><%= 'Instructor' %></th>
<th align="left" width="10%"><%= 'Room' %></th>
<th align="left" width="5%"><%= 'Day' %></th>
<th align="left" width="5%"><%= 'Units' %></th>
<th align="left" width="15%"><%= 'Time' %></th>
<th align="left" width="10%"><%= 'Limitations' %></th>
</tr>
<%= render :partial => #search_show.courses %>
</table>
From the courses controller (this has the #search_show variable).
def index
#courses = Course.order(sort_column + " " + sort_direction)
#search = Search.new
#search_show = Search.last
#title = "List"
#days = params[:days]
Finally, the _course.html.erb partial:
<tr>
<td><%= course.name %></td>
<td><%= course.number %></td>
<td><%= course.instructor %></td>
<td><%= course.room %></td>
<td><%= course.day %></td>
<td><%= course.units %></td>
<td><%= course.time %></td>
<td><%= course.limitations %></td>
<td><%= link_to 'Show', course %></td>
</tr>
This is not really an answer, but there is some problems with how you are trying to access your #days variable you set in the controller.
# your controller
...
def index
...
#days = params[:days]
# your model
...
private
def day_conditions
["courses.day LIKE ?", "%"+ #days.join("%")+"%"]
end
The #days, in your model, you are calling is not going to access the #days in your controller. Each #days belongs to their respective instances.
You should find a method of sending the #days from your controller into your models, instead of using global variables.
Solved the problem by using a $days global variable instead of #days.

Resources