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')
Related
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 ?
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])
Please help me figure out what I am doing wrong here! I am using s3_direct_upload to upload a basic image to Amazon S3 and then POST to create a record. I can see in the Network tab (firebug) that it is being POST'd. However, I'm not sure why the params are not being added to the DB.
This is what I am getting back:
Started POST "/choices" for 127.0.0.1 at 2013-10-02 17:36:10 -0700
Processing by ChoicesController#create as */*
Parameters: {"url"=>"https://mybucket.s3.amazonaws.com/uploads%2F1380760569802-bneiuk2ghf4-22e59d1c8959be731bc71e31f0a9d7c6%2Fslide0003_image002.jpg",
"filepath"=>"/uploads%2F1380760569802-bneiuk2ghf4-22e59d1c8959be731bc71e31f0a9d7c6%2Fslide0003_image002.jpg",
"filename"=>"slide0003_image002.jpg",
"filesize"=>"73930",
"filetype"=>"image/jpeg",
"unique_id"=>"bneiuk2ghf4",
"choice"=>{
"image"=>"https://mybucket.s3.amazonaws.com/uploads%2F1380760569802-bneiuk2ghf4-22e59d1c8959be731bc71e31f0a9d7c6%2Fslide0003_image002.jpg"
}
}
(0.3ms) BEGIN
(0.4ms) ROLLBACK
Rendered choices/create.js.erb (0.1ms)
Completed 200 OK in 16ms (Views: 6.2ms | ActiveRecord: 0.6ms)
# app/controllers/choice.rb
def create
#choice = Choice.create(choice_params)
end
def choice_params
params.require(:choice).permit!
end
Then my form (some HTML omitted for brevity):
#app/views/new.html.erb
<%= s3_uploader_form callback_url: choices_url, callback_param: "choice[image]", id: "s3-uploader" do %>
<%= file_field_tag :file, multiple: true %>
<% end %>
Any help would be great!
From the 'ROLLBACK", It looks like you are not saving the record. Perhaps, some validations are not being met. Change
#choice = Choice.create(choice_params)
to
#choice = Choice.create!(choice_params)
So that you can get back information concerning why your record is not being saved.
It seems that my "create" action isn't sending the information that I am entering in my "new" view. I have a route called
localhost:3000/zips
I have a view for the new page
<h1>
Zip Code Eligibility <font color="green">Add Zip Code</font>
</h1>
<p>
To <span class="hi">ADD</span> a zip code from the local delivery service, please enter the 5 digit zip code (6 in Canada) and click submit.
</p>
<%= form_for #zip do |z| %>
<p><%= z.label :zip %> <%= z.text_field :zip %> |
<%= z.label :state %> <%= z.text_field :state %>
</p>
<p><%= z.submit "Add Zip Code" %></p>
<% end %>
This is my zips_copntroller
class ZipsController < ApplicationController
def index
#zips = Zip.all
end
def show
#zip = Zip.find(params[:id])
end
def new
#zip = Zip.new
end
def create
#zip = Zip.new(params[:post])
if #zip.save
redirect_to zips_path, :notice => "Zipcode was saved sucessfully"
else
render "new"
end
end
def edit
end
def update
end
def destroy
end
end
Now when I enter "91202' and then 'CA' I click submit...it submits and redirects to the index view
<h1>
Pick-up/Delivery Eligibility
</h1>
<h3>
Based on U.S. Zipcode, Canadian Postal Code
</h3>
<p class="el">
To find out if you qualify for 4overs local delivery service,
please enter your <nobr>U.S. 5 digit zip code, or</nobr> your
<nobr>Canadian 6 character Postal Code,</nobr> then click submit.
<h4>Current Eligible Zip Codes</h4>
<!-- Possible sample code for the display page when I get around to the search function -->
<% #zips.each do |zip| %>
<!--"link_to" creates a link...first param is what you want to "display"...the second parameter
is what you want to link to here it's a shortcut called "zip" (which passes the entrie POST and Rails will create the page with it's contents)
-->
<p><%= link_to zip.zip, zip %>|<%= zip.state %></p>
<hr />
<% end %>
<p><%= link_to "Add a New Zip", new_zip_path %></p>
But it doesn't display the zip and state I have entered ... it displays this (image attached)
Here is the dump of the log...
Started POST "/zips" for 192.168.188.50 at 2013-08-03 12:51:42 -0700
Processing by ZipsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"wP8eOqMzOjLfLZjmq62EXdO0C59fHyRk3C/Y4b+96mA=", "zip"=>{"zip"=>"91202", "state"=>"CA"}, "commit"=>"Add Zip Code"}
(0.3ms) BEGIN
SQL (0.7ms) INSERT INTO "zips" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 Aug 2013 19:51:42 UTC +00:00], ["updated_at", Sat, 03 Aug 2013 19:51:42 UTC +00:00]]
(2.6ms) COMMIT
Redirected to http://chrish.sbx.4over.com:3000/zips
Completed 302 Found in 8ms (ActiveRecord: 3.6ms)
Started GET "/zips" for 192.168.188.50 at 2013-08-03 12:51:42 -0700
Processing by ZipsController#index as HTML
Zip Load (0.5ms) SELECT "zips".* FROM "zips"
Rendered zips/index.html.erb within layouts/application (2.7ms)
Completed 200 OK in 8ms (Views: 6.5ms | ActiveRecord: 0.5ms)
Started GET "/assets/application.css?body=1" for 192.168.188.50 at 2013-08-03 12:51:42 -0700
Started GET "/assets/zips.css?body=1" for 192.168.188.50 at 2013-08-03 12:51:42 -0700
Started GET "/assets/jquery.js?body=1" for 192.168.188.50 at 2013-08-03 12:51:42 -0700
Started GET "/assets/zips.js?body=1" for 192.168.188.50 at 2013-08-03 12:51:42 -0700
Started GET "/assets/turbolinks.js?body=1" for 192.168.188.50 at 2013-08-03 12:51:42 -0700
Started GET "/assets/jquery_ujs.js?body=1" for 192.168.188.50 at 2013-08-03 12:51:42 -0700
Started GET "/assets/application.js?body=1" for 192.168.188.50 at 2013-08-03 12:51:42 -0700
Any reason why the :post didn't send the POST information?
I am using Rails 4.0.0, and Ruby 1.9.3p448:
[freedel#chrish.sbx.4over.com localdel]$ rails --version
Rails 4.0.0
[freedel#chrish.sbx.4over.com localdel]$ ruby --version
ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-linux]
As log is saying, you will be able to receive form parameters as params[:zip]. So replace params[:post] to params[:zip].
And if you are using rails4, you will have to permit the parameters as you are mass assigning the attributes.
In your controller:
def create
#zip = Zip.new(zip_params)
if #zip.save
redirect_to zips_path, :notice => "Zipcode was saved sucessfully"
else
render "new"
end
end
...
private
def zip_params
params.require(:zip).permit(:zip, :state)
end
Since these are just two attributes, You can change your create method to this & it will work:
def create
#zip = Zip.new(zip: params[:zip][:zip], state: params[:zip][:state] )
if #zip.save
redirect_to zips_path, :notice => "Zipcode was saved sucessfully"
else
render "new"
end
end
But if you have more attibutes use Strong Params
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'