NoMethodError in StaticPages#home when attempting to list database query - html

Ruby noob here, I created a search form and I am trying to query a db and display the results. I am getting NoMethodError in StaticPages#home
along with....
/home/action/Projects/CodonCoderTest5/app/views/static_pages/home.html.erb where line #4 raised:
undefined method `each' for nil:NilClass
Where am I going wrong?
layouts/StaticPages/home
<h1>StaticPages#home</h1>
<% #data_bases.each do |list| %>
<div class="list">
<h1 class="list-mrnaCodon"><%= link_to list.mrnaCodon %></h1>
</div>
<% end %>
controller
class DataBaseController < ApplicationController
def new
end
def index
if params[:search]
#data_bases = Match.search(params[:search]).order("created_at DESC")
else
#data_bases = Match.order("created_at DESC")
end
end
end

The error means that #data_bases in your view is evaluating to nil. That makes sense, since the only way the view for StaticPages#home would have access to that variable is if it were set in the corresponding controller action (i.e. the home method on the StaticPagesController). Looks like you're only setting that variable on the DataBaseController.
class StaticPagesController < ApplicationController
...
def home
if params[:search]
#data_bases = Match.search(params[:search]).order("created_at DESC")
else
#data_bases = Match.order("created_at DESC")
end
end
...
end

Related

undefined method `user_revisers_path' "NoMethodError in Revisers#new "

I got this weird error I'm assuming this comes from the routes.rb part of my app. Im trying to give the chance for a user to become a reviser when they enter a form. a user can only become a reviser once so its a has_one reviser on user.rb model Thanks!
routes.rb:
Rails.application.routes.draw do
root 'pages#home'
devise_for :users ,
:path => '' ,
:path_names => { :sign_in => 'login', :sign_out => 'logout', :edit => 'profile' },
:controllers => { :omniauth_callbacks => 'omniauth_callbacks',
:registrations => 'registrations'
}
resources :users, only: [:index, :show] do
resource :reviser
end
revisers_controller:
class RevisersController < ApplicationController
before_action :set_reviser, only: [:show, :edit, :update]
before_action :authenticate_user!, except: [:show]
def index
#reviser = current_user.reviser
end
def show
end
def new
#reviser = current_user.build_reviser(params[:reviser])
#user = User.find(params[:user_id])
end
def create
#reviser = current_user.reviser.build(reviser_params)
if #reviser.save
redirect_to #reviser,notice: "saved...."
else
render :new
end
end
def edit
set_reviser
end
def update
set_reviser
if #reviser.update(reviser_params)
redirect_to #reviser, notice: "updated.."
else
render :edit
end
end
private
def set_reviser
#reviser = Reviser.find(params[:id])
end
def reviser_params
params.require(:reviser).permit(:description, :average_start, :average_end, :max_pages, :price_per, :active)
end
end
new.html
<%= form_for [current_user, #reviser] do |f| %>
<div class="row">
<div class="div.col-md-4 select">
<div class="form-group">
<label>dsd</label>
<%= f.input :description, label: false, class: 'controls',:input_html => { :id => 'description' } %>
</div>
</div>
</div>
<%= f.submit "Become Adviser", class: "btn btn-large btn-primary" %>
<% end %>
Error log:
Rendered revisers/_form.html.erb (14.7ms)
Rendered revisers/new.html.erb within layouts/application (15.9ms)
Completed 500 Internal Server Error in 48ms (ActiveRecord: 1.1ms)
ActionView::Template::Error (undefined method `user_revisers_path' for #<#<Class:0x007faf35f0cc60>:0x007faf35ee7e60>):
5: <div class="panel-body">
6: <div class="container">
7:
8: <%= form_for [current_user, #reviser] do |f| %>
9:
10: <div class="row">
11: <div class="div.col-md-4 select">
app/views/revisers/_form.html.erb:8:in `_app_views_revisers__form_html_erb___2471522092853631188_70195335070980'
app/views/revisers/new.html.erb:1:in `_app_views_revisers_new_html_erb___1451348464463745171_70195280947160'
Rake routes:
Prefix Verb URI Pattern Controller#Action
root GET / pages#home
new_user_session GET /login(.:format) devise/sessions#new
user_session POST /login(.:format) devise/sessions#create
destroy_user_session DELETE /logout(.:format) devise/sessions#destroy
user_omniauth_authorize GET|POST /auth/:provider(.:format) omniauth_callbacks#passthru {:provider=>/facebook/}
user_omniauth_callback GET|POST /auth/:action/callback(.:format) omniauth_callbacks#(?-mix:facebook)
user_password POST /password(.:format) devise/passwords#create
new_user_password GET /password/new(.:format) devise/passwords#new
edit_user_password GET /password/edit(.:format) devise/passwords#edit
PATCH /password(.:format) devise/passwords#update
PUT /password(.:format) devise/passwords#update
cancel_user_registration GET /cancel(.:format) registrations#cancel
user_registration POST / registrations#create
new_user_registration GET /sign_up(.:format) registrations#new
edit_user_registration GET /profile(.:format) registrations#edit
PATCH / registrations#update
PUT / registrations#update
DELETE / registrations#destroy
user_confirmation POST /confirmation(.:format) devise/confirmations#create
new_user_confirmation GET /confirmation/new(.:format) devise/confirmations#new
GET /confirmation(.:format) devise/confirmations#show
user_reviser POST /users/:user_id/reviser(.:format) revisers#create
new_user_reviser GET /users/:user_id/reviser/new(.:format) revisers#new
edit_user_reviser GET /users/:user_id/reviser/edit(.:format) revisers#edit
GET /users/:user_id/reviser(.:format) revisers#show
PATCH /users/:user_id/reviser(.:format) revisers#update
PUT /users/:user_id/reviser(.:format) revisers#update
DELETE /users/:user_id/reviser(.:format) revisers#destroy
users GET /users(.:format) users#index
user GET /users/:id(.:format) users#show
photos GET /photos(.:format) photos#index
POST /photos(.:format) photos#create
new_photo GET /photos/new(.:format) photos#new
edit_photo GET /photos/:id/edit(.:format) photos#edit
photo GET /photos/:id(.:format) photos#show
PATCH /photos/:id(.:format) photos#update
PUT /photos/:id(.:format) photos#update
DELETE /photos/:id(.:format) photos#destroy
pages GET /pages(.:format) pages#index
POST /pages(.:format) pages#create
new_page GET /pages/new(.:format) pages#new
edit_page GET /pages/:id/edit(.:format) pages#edit
page GET /pages/:id(.:format) pages#show
PATCH /pages/:id(.:format) pages#update
PUT /pages/:id(.:format) pages#update
DELETE /pages/:id(.:format) pages#destroy
autocomplete_user_country_suggestions GET /suggestions/autocomplete_user_country(.:format) suggestions#autocomplete_user_country
autocomplete_user_city_suggestions GET /suggestions/autocomplete_user_city(.:format) suggestions#autocomplete_user_city
autocomplete_user_school_suggestions GET /suggestions/autocomplete_user_school(.:format) suggestions#autocomplete_user_school
autocomplete_user_major_suggestions GET /suggestions/autocomplete_user_major(.:format) suggestions#autocomplete_user_major
suggestions GET /suggestions(.:format) suggestions#index
POST /suggestions(.:format) suggestions#create
new_suggestion GET /suggestions/new(.:format) suggestions#new
edit_suggestion GET /suggestions/:id/edit(.:format) suggestions#edit
suggestion GET /suggestions/:id(.:format) suggestions#show
PATCH /suggestions/:id(.:format) suggestions#update
PUT /suggestions/:id(.:format) suggestions#update
DELETE /suggestions/:id(.:format) suggestions#destroy
conversation_messages GET /conversations/:conversation_id/messages(.:format) messages#index
POST /conversations/:conversation_id/messages(.:format) messages#create
conversations GET /conversations(.:format) conversations#index
POST /conversations(.:format) conversations#create
post_comments GET /posts/:post_id/comments(.:format) comments#index
POST /posts/:post_id/comments(.:format) comments#create
new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new
edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) comments#edit
post_comment GET /posts/:post_id/comments/:id(.:format) comments#show
PATCH /posts/:post_id/comments/:id(.:format) comments#update
PUT /posts/:post_id/comments/:id(.:format) comments#update
DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
post_places GET /posts/:post_id/places(.:format) places#index
POST /posts/:post_id/places(.:format) places#create
new_post_place GET /posts/:post_id/places/new(.:format) places#new
edit_post_place GET /posts/:post_id/places/:id/edit(.:format) places#edit
post_place GET /posts/:post_id/places/:id(.:format) places#show
PATCH /posts/:post_id/places/:id(.:format) places#update
PUT /posts/:post_id/places/:id(.:format) places#update
DELETE /posts/:post_id/places/:id(.:format) places#destroy
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
You have a singular resource definition for your :reviser route. This makes sense for what you're trying to do, however the route generated by form_for [current_user, #reviser] will try to generate a route with both a :user_id, and an :id to identify your reviser.
So, the :id field isn't defined in your case since resource :reviser doesn't create an :id.
The solution is to explicitly set the url in your form_for to the route your want:
It should be something along the lines of:
form_for #reviser, url: edit_user_reviser_path(user_id: current_user.id)
The bigger issue with your code is that you're still directly referencing reviser by id in your controller. Under your current route settings, this will return an error on the Reviser.find() method. However, more importantly this presents a security concern since a malicious user could send an id param in the PATCH request to hijack and update a record that belongs to another user.
A simple solution is to just reference the reviser object directly on current_user.
def set_reviser
#reviser = current_user.reviser
end

How to put variables into HTML from ruby on rails

I tried to use a variable in HTML which is calculated from ruby code and MSSQL
This is my Ruby code to get #result
class StartingController < ApplicationController
before_action :require_user, only: [:index, :start]
attr_reader :table
attr_writer :table
def initialize
#table = Hash.new()
#connection = ActiveRecord::Base.connection
#st='exec search '
end
def start
.... some code set #st values
#result = #connection.exec_query(#st)
#table = #result[0]
redirect_to '/results'
end
end
def index
end
def results
end
end
This is the HTML which need to use #result
<% #result.each do |x| %>
<tr>
s: <td><%= x %></td>
</tr>
<% end %>
But I always get
undefined method `each' for nil:NilClass
if I
puts #result
I can get correct value
Can anyone help?
Problem is the instance variables(and variables) only accessible within an action, and your redirect_to actually change the action from start to results, so #results is not initialized.
I assume that you have a view at views/start/result.html.erb.
The best solution for this is you can remove the action results, and call render :results instead of redirect_to.

Ruby on Rails MySQL select page undefined method `each' for nil:NilClass

I've recently migrated my webpage internally at my company to Ruby on Rails, and I've got mysql setup and reading, but I'm currently trying to setup a webpage, and display some basic information I am getting this undefined method `each' error. If anyone can lend me a hand it would be useful, I feel like I'm just missing something, and once I get this sorted I can stuck plugging away!
NoMethodError in Index#toolkit
Showing /rhel5pdi/apollo/var/env/BlackMesaRails/rails-root/app/views/index/toolkit.html.erb where line #9 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #9):
6: <h3>Toolkit</h3>
7: </div>
8: <p>
9: <% #toolkit_urls.each do |toolkit| %>
10: <div class="page-header"><h3><%= raw toolkit.name %></h3></div>
11: <p><%= raw toolkit.url %></p>
12: <% end %>
Rails.root: /rhel5pdi/apollo/var/env/BlackMesaRails/rails-root
Application Trace | Framework Trace | Full Trace
app/views/index/toolkit.html.erb:9:in `_app_views_index_toolkit_html_erb___2469700212325674377_127789780760'
Request
Parameters:
None
Show session dump
Show env dump
Response
Headers:
None
I'll display my Model, view, and controller
index_controller.rb
class IndexController < ApplicationController
before_filter :initialize_remote_user
def index
end
def toolkit
#toolkit_urls = HelpToolkit.order(:name)
end
end
toolkit.html.erb
<body>
<div class="col-md-9">
<div class="well sales-pitch">
<div class="page-header">
<h3>Toolkit</h3>
</div>
<p>
<% #toolkit_urls.each do |toolkit| %>
<div class="page-header"><h3><%= raw toolkit.name %></h3></div>
<p><%= raw toolkit.url %></p>
<% end %>
</p>
</div>
</div>
</body>
help_toolkit.rb (Model)
class HelpToolkit < ActiveRecord::Base #class beginning
attr_accessible :id, :url, :name
end
I may be wrong, but it looks like you are not assigning the variable in the index method:
def index
#assign variable here! Or call the toolkit method here
end
def toolkit
#toolkit_urls = Toolkit.select('url, name').from('test.help_toolkit').order('name')
end
Edit:
Nope sorry. Misread the action name....
I believe this
def toolkit
#toolkit_urls = HelpToolkit.All
end
should be
def toolkit
#toolkit_urls = HelpToolkit.all
end
I have corrected my issue. The Model was looking for the plural table name, so it was looking for help_toolkits, so what I had to do was modify the environment.rb file to make table_pluralization = false. Doing this solved my issue.

Odd rendering of an html table in Ruby on Rails when using content_tag

I'm trying to build a table in Ruby on Rails with the help of the content_tag method.
When I run this:
def itemSemanticDifferential(method, options = {})
if options[:surveyQuestion].any? then
#template.content_tag(:tr) do
#template.content_tag(:td, options[:surveyQuestion], :colspan => 3)
end
end
#template.content_tag(:tr) do
#template.content_tag(:th, options[:argument0])
end
end
Only the second part gets rendered:
#template.content_tag(:tr) do
#template.content_tag(:th, options[:argument0])
end
Can anyone tell me why this is?
Ruby Rails returns the last variable it used if no return is explicitly called.
( example: )
def some_method(*args)
a = 12
b = "Testing a String"
# ...
3
end # This method will return the Integer 3 because it was the last "thing" used in the method
Use an Array to return all the content_tag (WARNING: this method will return an Array, not a content_tag as you expect, you'll need to loop on it):
def itemSemanticDifferential(method, options = {})
results = []
if options[:surveyQuestion].any? then
results << #template.content_tag(:tr) do
#template.content_tag(:td, options[:surveyQuestion], :colspan => 3)
end
end
results << #template.content_tag(:tr) do
#template.content_tag(:th, options[:argument0])
end
return results # you don't actually need the return word here, but it makes it more readable
end
As asked by author of the Question, You need to loop on the result because it is an array of content_tags. Also, you need to use .html_safe to output the content_tags as HTML (not strings).
<% f.itemSemanticDifferential(:method, options = {}).each do |row| %>
<%= row.html_safe %>
<% end %>

Referencing the session controller from the user controller to check if a user is logged in

NoMethodError in UsersController#show
undefined method `signed_in?' for #<UsersController:0x5bf3980>
Rails.root: C:/test_app
Application Trace | Framework Trace | Full Trace
app/controllers/users_controller.rb:91:in `signed_in_user'
Request
Parameters:
{"id"=>"1"}
Show session dump
Show env dump
Response
Headers:
None
In Users_Controller
def signed_in_user
redirect_to signin_path, notice: "Please Sign In." unless signed_in?
end
In SessionsController
def signed_in?
!current_user.nil?
end
module SessionsHelper
def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
self.current_user = user
end
def sign_out
cookies.delete(:remember_token)
self.current_user = nil
end
def current_user=(user)
#current_user = user
end
def current_user
#current_user ||= user_from_remember_token
end
def signed_in?
!current_user.nil?
end
def create
user = User.authenticate(params[:session][:email],
params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password combination."
#title = "Sign In"
render 'new'
else
sign_in user
flash.now[:error] = "Welcome, #{user.name}"
render 'AdCon'
end
end
def destroy
sign_out
redirect_to root_path
end
private
def user_from_remember_token
User.authenticate_with_salt(*remember_token)
end
def remember_token
cookies.signed[:remember_token] || [nil,nil]
end
end
*EDIT:*************************************************
I'm using the tutorial on:
http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users # Listing 9.12
Listing 9.12. Adding a signed_in_user before filter.
app/controllers/users_controller.rb
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:edit, :update]
.
.
.
private
def signed_in_user
redirect_to signin_path, notice: "Please sign in." unless signed_in?
end
end
When I included the helper in the SessionsController I received the message
undefined method `signed_in?' for #
Extracted source (around line #9):
<div>
<% if controller.signed_in? %> <----LINE 9
<%= link_to "Sign Out", signout_path, :method => :delete %>
<% else %>
<%= link_to "Sign IN" , signin_path %>
I included the Helper like this:
class SessionsController < ApplicationController
include SessionsHelper
I couldn't get this to work, so I copied the helper methods into SessionsController and the error went away.and now I'm having an issue with 9.12 where signed_in? is an unknown method. and it makes sense because signed_in? is in SessionsController via a helper. can the UserController access that function. I'm new to rails and confused.
thanks for all the feedback
EDIT:******************
Here is the ApplicationController
class ApplicationController < ActionController::Base
protect_from_forgery
include ActionView::Helpers::SessionsHelper
private
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
end
You're declaring your shared methods in the wrong place. signed_in? should be defined inside your ApplicationController, which is the shared base class for all your other controllers. There is, in essence, no way for you to do what you're trying to do. The UsersController can't access your SessionController's methods, nor should it be able to. That isn't how controllers work.
current_user, current_user=, and signed_in? all belong in your ApplicationController, not your SessionsController, because they're shared methods meant to be used by all your controllers which inherit from ApplicationController.
I figured out, I had a sessionhelper file from another project open and I was editing that one instead of the one associated with my current project. Thanks for the help.