undefined method `user' for nil:NilClass in Ruby Tokbox API - ruby-on-rails

i am trying to use the tokbox api and have the following error:
Started GET "/en/stream" for 127.0.0.1 at 2018-06-02 18:38:57 +0800
Processing by UsersController#stream as HTML
Parameters: {"locale"=>"en"}
Rendering users/stream.html.erb within layouts/application
Rendered users/stream.html.erb within layouts/application (3.8ms)
Completed 500 Internal Server Error in 34ms (ActiveRecord: 0.3ms)
ActionView::Template::Error (undefined method `user' for nil:NilClass):
1: <%= javascript_include_tag "//static.opentok.com/webrtc/v2.2/js/TB.min.js" %>
2: <h1>Your stream</h1>
3: <div id="publisher"></div>
4: Link to your stream: <%= link_to watch_url(#stream.user.id), watch_url(#stream.user.id) %>
app/views/users/stream.html.erb:4:in `_app_views_users_stream_html_erb__3447765015494674598_70186549432640'
My User/stream.html.erb looks like:
<%= javascript_include_tag "//static.opentok.com/webrtc/v2.2/js/TB.min.js" %>
<h1>Your stream</h1>
<div id="publisher"></div>
Link to your stream: <%= link_to watch_url(#stream.user.id), watch_url(#stream.user.id) %>
My UserController looks like :
def stream
#stream = User.find(params[:id]).stream
#stream = current_user.stream || current_user.create_stream
gon.opentok = opentok_data(#stream)
end
def watch
#stream = User.find(params[:id]).stream
gon.opentok = opentok_data(#stream)
end
private
def opentok_data(stream)
token = OpenTokClient.generate_token(stream.opentok_session_id)
{ sessionId: stream.opentok_session_id, apiKey: Figaro.env.opentok_api_key, token: token }
end
My user model has one stream, and my stream model has one user.
Does anyone knows why it is not recognising the user ?

Related

Rails 5.0.1 Rendering to Excel not working

I have an app that helps a school to track students attendance to sports practices and games, I have all my index actions to render html, csv and xls formats and EVERYTHING GOES WELL. I have a special report that uses several model relations to complete, I am not required to render csv (I think this will be too complex to implement the to_csv method, I don't even have a clue where to put it, but this is not my problem), Now I created the equipos_controller#forma_rep method and a related view with a form to get the report's parameters, as you can see in the routes and controller code, it works fine when the report action renders the default HTML as you can see in the following log, parameters from the 'forma_rep.html.erb' form are in the params array..
Started POST "/equipos/reporte_asist" for 127.0.0.1 at 2017-01-05 18:37:51 -0600
Processing by EquiposController#reporte_asist as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"IP1O2bSgkGcSaUn5Sf9Tnp30yzxfP10+cA0h/1+XudoR7W8SoP6xveP3fwJpLFTvyRaBFdtqsqz5pCfYID5b5Q==", "entrenador"=>"1", "inicio"=>"2016-12-12", "final"=>"2016-12-20", "commit"=>"Crear Reporte"}
... most SQL ommited
Rendering equipos/reporte_asist.html.erb within layouts/application
Rendered equipos/reporte_asist.html.erb within layouts/application (69.4ms)
Rendered layouts/_shim.html.erb (0.5ms)
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Rendered layouts/_header.html.erb (5.9ms)
Rendered layouts/_footer.html.erb (1.1ms)
Completed 200 OK in 210ms (Views: 165.2ms | ActiveRecord: 5.6ms)
But when I click the "Excel" link :
Started POST "/equipos/reporte_asist.xls" for 127.0.0.1 at 2017-01-05 18:37:56 -0600
Processing by EquiposController#reporte_asist as XLS
Parameters: {"authenticity_token"=>"oYVjNfxN5Qxt9FHC6PpeU0wQenD3p+otaxcGts1kZRuQlUL+6 BPE1pxqZznIKVkiGPIwWXPyBb/ivgCRss2HJA=="}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Equipo Load (0.2ms) SELECT "equipos".* FROM "equipos" WHERE "equipos"."user_id" = ? [["user_id", 1]]
Completed 500 Internal Server Error in 11ms (ActiveRecord: 0.4ms)
NoMethodError (undefined method `<<' for nil:NilClass):
app/controllers/equipos_controller.rb:96:in `block in reporte_asist'
app/controllers/equipos_controller.rb:95:in `reporte_asist'
I can see that the parameters are not complete when I click the Excel link in the html file, how can I send them again? my routes work fine with the html version and the #index action renders fine in all formats, please help me.
Here is all code involved.
Routes:
resources :categorias
get '/equipos/forma_rep'
post '/equipos/reporte_asist', to: 'equipos#reporte_asist', as: 'reporte_asist'
resources :equipos
resources :players
app/controllers/equipos_controller.rb
def index
#equipos = Equipo.paginate(page: params[:page])
respond_to do |format|
format.html
format.csv { send_data #equipos.to_csv }
format.xls
end
end
# GET /equipos/forma_rep
def forma_rep
#equipo = Equipo.new
#entrenadores = User.all
end
# PUT /equipos/reporte_asist
def reporte_asist
if params[:entrenador]
#entrenador = User.find(params[:entrenador].to_i)
inicio = Time.parse(params[:inicio])
final = Time.parse(params[:final])
#equipos = #entrenador.equipos
#eventos = reporte(#entrenador.id, inicio, final)
else
#entrenador = current_user
#equipos = #entrenador.equipos
#equipos.each do |equi|
#eventos << equi.eventos
end
end
respond_to do |format|
format.html
format.xls
end
end
I have created the app/views/equipos/reporte_asist.xls.erb file with the XML directives as in..
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<Worksheet ss:Name="Asistencias">
<Table>
<Row>
<Cell><Data ss:Type="String">Entrenador:</Data></Cell>
<Cell><Data ss:Type="String"><%= #entrenador.name %></Data> </Cell>
</Row>
....etc.
And this is the link I have in the app/views/equipos/reporte_asist.html.erb
<p>
Descargar:
<%= link_to "Excel", reporte_asist_path(format: "xls"), method: :post %>
</p>
Of course I have defined the Mime:Type.register in the config/initializers/mime_types.rb and requested the 'csv' library in my config/application.rb . I am using Rails 5.0.0.1 and Ruby 2.3.1 ...
This is the code that collects report parameter from user, it is inside the app/views/equipos/forma_rep.html.erb that posts to the reporte_asist.html.erb:
<h1>Reporte de Asistencias</h1>
<%= form_tag(reporte_asist_path) do %>
<%= label_tag(:entrenador, "Entrenador:") %>
<%= select_tag :entrenador, options_from_collection_for_select(#entrenadores, "id", "name"), prompt: "Seleccione el entrenador", class: 'form-control' %>
<%= label_tag(:inicio, "Fecha inicial de reporte:") %>
<%= date_field_tag :inicio, class: 'form-control' %>
<%= label_tag(:final, "Fecha final de reporte:") %>
<%= date_field_tag :final, class: 'form-control' %>
<%= submit_tag "Crear Reporte", class: "btn btn-default" %>
<% end %>
</div>
Initially this is the code that sends the report parameters, but once in the report view I cannot (and don't want to) re-render the form, that's why I put the link_to to the same controller but trying to render the excel
Add the parameters you want to POST to your reporte_asist_path helper, like this:
reporte_asist_path(format: 'xls', entrenador_id: #entrenador.id)
More information can be found here:
http://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for
Also note that while using POST method for links is supported by Rails, it relies on JavaScript. If the user has JavaScript disabled, the request will fall back to GET method. So it's safer to use forms.

rails partial doesn't receive variable

My application has a Server and Domain modules such that server has_many domains and domain belongs_to server.
I'm trying to render a partial in the Server controller:
def get_domain_checkboxes
#domains = Domain.find_by(:server_id => params[:id])
render :partial => 'servers/domain_checkboxes', :layout => nil
end
The partial '_domain_checkboxes.html.erb' contains:
<% #domains.each do |domain| %>
domain.url
<% end %>
But I get an error when going to 'servers/3/get_domain_checkboxes' route and the trace says:
Started GET "/servers/3/get_domain_checkboxes" for ::1 at 2015-12-18 05:03:08 +0200
Processing by ServersController#get_domain_checkboxes as HTML
Parameters: {"server_id"=>"3"}
Domain Load (0.3ms) SELECT "domains".* FROM "domains" WHERE "domains"."server_id" IS NULL LIMIT 1
Rendered servers/_domain_checkboxes.html.erb (1.4ms)
Completed 500 Internal Server Error in 9ms (ActiveRecord: 0.4ms)
ActionView::Template::Error (undefined method `each' for nil:NilClass):
1: <% #domains.each do |domain| %>
2: hello
3: <% end %>
app/views/servers/_domain_checkboxes.html.erb:1:in `_app_views_servers__domain_checkboxes_html_erb___2806237560631891313_70206341448100'
app/controllers/servers_controller.rb:71:in `get_domain_checkboxes'
Tried anything for past hour. Probably something simple that I'm missing?
EDIT:
Tried #domains = Domain.find_by(:server_id => params[:server_id]) instead but still get an error:
Started GET "/servers/3/get_domain_checkboxes" for ::1 at 2015-12-18 05:09:43 +0200
Processing by ServersController#get_domain_checkboxes as HTML
Parameters: {"server_id"=>"3"}
Domain Load (0.1ms) SELECT "domains".* FROM "domains" WHERE "domains"."server_id" = ? LIMIT 1 [["server_id", 3]]
Rendered servers/_domain_checkboxes.html.erb (1.6ms)
Completed 500 Internal Server Error in 3ms (ActiveRecord: 0.1ms)
ActionView::Template::Error (undefined method `each' for #<Domain:0x007fb465810738>):
1: <% #domains.each do |domain| %>
2: hello
3: <% end %>
app/views/servers/_domain_checkboxes.html.erb:1:in `_app_views_servers__domain_checkboxes_html_erb___2806237560631891313_70206341448100'
app/controllers/servers_controller.rb:71:in `get_domain_checkboxes'
You need to change:
#domains = Domain.find_by(:server_id => params[:id])
to
#domains = Domain.where(:server_id => params[:server_id])

Error validating signup form using tableless implementation

I'm trying to implement a signup form. See this screenshot. I'm using the LearnRails tutorial to help me.
It works when you type in a valid email address. However, if you don't type in a valid email address, it's giving me this error: undefined method 'empty?' for nil:NilClass. My logs say this:
ActionView::Template::Error (undefined method `name' for nil:NilClass):
1: <% content_for(:title, "#{#college.name} Student Reviews" + " | #{params[:section1]} | #{params[:section2]}".titleize) %>
2: <% description "#{#question}" %>
3:
4: <div id="college_pages_css">
app/views/college_pages/disqus_normal.html.erb:1:in `_app_views_college_pages_disqus_normal_html_erb___3963356040782610986_70269489097160'
Which is weird because it should be redirecting to my home page, which doesn't have the #college variable.
Note: I'm using the activerecord-tableless gem, because the tutorial uses it.
Model
class Subscriber < ActiveRecord::Base
attr_accessible :email
has_no_table
column :email, :string
validates_presence_of :email
validates_format_of :email,
:with => /\A[-a-z0-9_+\.]+\#([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i
def subscribe
mailchimp = Gibbon::API.new(ENV['MAILCHIMP_API_KEY'])
result = mailchimp.lists.subscribe({
:id => ENV['MAILCHIMP_LIST_ID'],
:email => {:email => self.email},
:double_optin => false,
:update_existing => true,
:send_welcome => true
})
Rails.logger.info("Subscribed #{self.email} to MailChimp") if result
end
end
Controller
class SubscriberController < ApplicationController
def create
#subscriber = Subscriber.new(params[:subscribe])
if #subscriber.valid?
#subscriber.subscribe
redirect_to root_path
else
render root_path
end
end
end
View
<%= simple_form_for :subscribe, url: 'subscribe' do |f| %>
<%= f.input :email, label: false %> <br/>
<%= f.button :submit, "Notify me", class: "btn btn-primary" %>
<% end %>
Note that the tutorial uses a secure_params method while I'm using attr_accessible. I wouldn't think that this would be a problem, but it's possible.
I was thinking of ignoring this issue, and just using client side validations, but that causes my site to crash. On the topic of client side validations, aren't HTML5 email input fields supposed to automatically validate?
How can I fix this issue?
Edit: Logs when I load the home page
Started GET "/" for 127.0.0.1 at 2014-04-01 16:15:47 -0400
Processing by StaticPagesController#home as HTML
Rendered static_pages/home.html.erb within layouts/application (3.6ms)
Completed 200 OK in 41ms (Views: 40.3ms | ActiveRecord: 0.0ms)
Started GET "/assets/jquery.ui.theme.css?body=1" for 127.0.0.1 at 2014-04-01 16:15:47 -0400
Started GET "/assets/jquery.ui.accordion.css?body=1" for 127.0.0.1 at 2014-04-01 16:15:47 -0400
.
.
.
Started GET "/favicon.ico" for 127.0.0.1 at 2014-04-01 16:15:49 -0400
Started GET "/favicon/academics/professors/1" for 127.0.0.1 at 2014-04-01 16:15:50 -0400
Processing by CollegePagesController#disqus_normal as */*
Parameters: {"college"=>"favicon", "section1"=>"academics", "section2"=>"professors", "question_id"=>"1"}
College Load (1.4ms) SELECT "colleges".* FROM "colleges" WHERE "colleges"."url" = 'favicon' LIMIT 1
Rendered college_pages/disqus_normal.html.erb within layouts/application (3.7ms)
Completed 500 Internal Server Error in 14ms
ActionView::Template::Error (undefined method `name' for nil:NilClass):
1: <% content_for(:title, "#{#college.name} Student Reviews" + " | #{params[:section1]} | #{params[:section2]}".titleize) %>
2: <% description "#{#question}" %>
3:
4: <div id="college_pages_css">
app/views/college_pages/disqus_normal.html.erb:1:in `_app_views_college_pages_disqus_normal_html_erb___3963356040782610986_70269489097160'
Rendered /Users/adamzerner/.rvm/gems/ruby-2.0.0-p451#global/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (80.6ms)
Rendered /Users/adamzerner/.rvm/gems/ruby-2.0.0-p451#global/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.6ms)
Rendered /Users/adamzerner/.rvm/gems/ruby-2.0.0-p451#global/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (98.3ms)
Started GET "/assets/favicon.ico" for 127.0.0.1 at 2014-04-01 16:15:50 -0400
disqus_normal action
def disqus_normal
#college = College.find_by_url(params[:college])
#question = get_question(params[:section2], params[:question_id])
end
The error
undefined method 'name' for nil:NilClass
is appearing on line 1 which is
<% content_for(:title, "#{#college.name} Student Reviews" + " | #{params[:section1]} | #{params[:section2]}".titleize) %>
of college_pages/disqus_normal.html.erb page.
It means that #college is nil and you are trying to access property name on a nil object. Hence, the error.
To resolve this make sure that you set the value of #college instance variable in the action from where you are redirecting to this page.
UPDATE
Also, there was an issue with routing.
get '/:college', to: redirect('/%{college}/academics/professors/1')
Because of the above problematic route GET "/favicon.ico" is getting converted to GET "/favicon/academics/professors/1" and disqus_normal is getting called. Ideally it would be better if you add some static text to the problematic route.
For example:
get '/college/:college', to: redirect('/%{college}/academics/professors/1')

Select_Tag not working in rails?

Here is my code for select_tag
<%= select_tag :tp, options_for_select([["movable",1],["fixed",2]]), :prompt => "select type of asset" %>
it works if i replace by:
<%= f.text_area :tp %>
If this in not enough i will give more code as you desire:
here is the log after i use select_tag
Started POST "/assets" for 127.0.0.1 at 2014-03-07 23:40:34 +0530
Processing by AssetsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Gib6rSODjXgXLZ9+5sDcq0ZatkA7144hU+Em2X7KONU=", "asset"=>{"name"=>"", "location"=>"", "cost"=>""}, "tp"=>"1","commit"=>"Save"}
(1.0ms) BEGIN
(1.0ms) ROLLBACK
Redirected to http://localhost:3000new
Completed 302 Found in 5ms (ActiveRecord: 2.0ms)
[2014-03-07 23:40:34] ERROR URI::InvalidURIError: the scheme http does not accept registry part: localhost:3000new (or bad hostname?)
F:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/uri/generic.rb:1203:in `rescue in merge'
F:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/uri/generic.rb:1200:in `merge'
F:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/webrick/httpresponse.rb:275:in `setup_header'
F:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/webrick/httpresponse.rb:205:in `send_response'
F:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/webrick/httpserver.rb:110:in'run'
F:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'
Started GET "/assets/logo.png" for 127.0.0.1 at 2014-03-07 23:40:36 +0530
Error after changing to `real_assets_path
Started GET "/real_assets/new" for 127.0.0.1 at 2014-03-09 13:56:47 +0530
ActiveRecord::SchemaMigrationLoad(1.0ms)SELECT"schema_migrations".* FROM"schema_migrations"
Processing by AssetsController#new as HTML
Rendered assets/new.html.erb within layouts/application (30.0ms)
Completed 500 Internal Server Error in 98ms
ActionView::Template::Error (undefined method `assets_path' for #<# <Class:0x545bb78>:0x545aeb8>):
1: <div class = "container">
2: <div id = "assetnew">
3: <%= form_for(#asset) do |f| %>
4: <center><h1>Add Asset</h1></center>
5: <div class = "well">
6: <a class ="red">
app/views/assets/new.html.erb:3:in`_app_views_assets_new_html_erb___457532114_11608392'
Rendered
F:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
Rendered
F:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
Rendered
F:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (18.0ms)
Assets
This is the error Rails is returning:
ERROR URI::InvalidURIError: the scheme http does not accept registry part: localhost:3000new (or bad hostname?)
Without seeing your form, it seems you've got an issue with calling your resource /assets (as mentioned in the comments)
Basically, Rails treats the assets pipeline as a base directory - localhost:3000/your_asset_file.png -- it looks like this is what's happening here
Because your app is referencing /assets, I would surmise it's confusing it with the assets dir. Try doing this:
#config/routes.rb
resources :assets, as: "real_assets", path: "real_assets" #-> real_assets_path - /real_assets
Select
The select problem is likely caused by your assets path problem
select_tag is a standalone helper method (doesn't need any FormBuilder to help it). This means you should be able to just use it in an .html.erb file without any problems
The syntax for the select looks okay, so I'd recommend if you get your assets path fixed, you should be able to use it

Dont understand why I'm encountering this TypeError (Can't convert nil into String)

Very simple process I'm trying to implement.
On a home page or landing page I want to capture emails for an email list.
If the email passes validation, it gets saved, Great! Everything works fine when there are no errors.
When there is an error like only inputting an 'a' character as shown in the log below. Or even just an empty string I continually get the same TypeError (can't convert nil to String)
Here is the log:
Started GET "/" for 127.0.0.1 at 2013-06-13 13:48:56 -0400
Connecting to database specified by database.yml
Processing by HighVoltage::PagesController#show as HTML
Parameters: {"id"=>"home"}
Rendered shared/_error_messages.html.erb (0.4ms)
Rendered layouts/_visitor_form.html.erb (7.9ms)
Rendered pages/home.html.erb within layouts/application (13.1ms)
Completed 200 OK in 82ms (Views: 39.6ms | ActiveRecord: 1.8ms)
[2013-06-13 13:48:57] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
Started POST "/visitors" for 127.0.0.1 at 2013-06-13 13:48:59 -0400
Processing by VisitorsController#create as HTML
Parameters: {"utf8"=>"✓",authenticity_token"=>"esTPNzNtkmNPTe7Jh+E2aDHNrgocU5Z8g49Nj0QiOhQ=", "visitor"=>{"email"=>""}, "commit"=>"Add to newsletter list"}
(0.1ms) begin transaction
Visitor Exists (0.2ms) SELECT 1 AS one FROM "visitors" WHERE LOWER("visitors"."email") = LOWER('') LIMIT 1
(0.1ms) rollback transaction
Completed 500 Internal Server Error in 39ms
TypeError (can't convert nil into String):
app/controllers/visitors_controller.rb:12:in `create'
Here is the visitors_controller.rb
def create
#visitor = Visitor.new(params[:visitor])
if #visitor.save
flash[:success] = "Your email has been added!"
redirect_to '/'
else
render '/'
end
end
I've also tried
#visitor = Visitor.new(:visitor => params[:visitor][:email])
and a few other sequences with no success.
How can I get the unsuccessful saves to gracefully show the validation errors and allow the user to resubmit.
Here is the layout:
<%= form_for Visitor.new do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.submit "Add to newsletter list", class: "btn btn-large btn-primary" %>
<% end %>
Maybe the high_voltage gem is screwing me up. I don't have enough experience to know.
UPDATE:
rake routes
visitors POST /visitors(.:format) visitors#create
home /home(.:format) pages#home
root / high_voltage/pages#show {:id=>"home"}
page GET /pages/*id high_voltage/pages#show
The problem is, render '/' does not render index page. You have to specify which action page you want to be rendered. According to your routes, this line should look like this:
render 'pages/home'

Resources