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.
Related
I have found many generic posts suggesting this has to do with redirects. I believe this may be due to how I have a form set up.
On the plans.html.erb page I have a form with four submits, each going to the same place with different params:
<%= form_with url: :affiliate_select_plan, class: "mx-auto" do |f| %>
<!-- Paid Plans -->
<% #plans.each_with_index do |plan, i| %>
<%= f.button 'Select Plan', value: plan[:name], type: 'submit' %>
<% end %>
<% end %>
I have the affiliate_select_plan_path setup in my routes.rb:
devise_scope :affiliate do
post 'affiliate/select_plan', :to => 'affiliates/registrations#select_plan'
end
The form successfully hits the select_plan method in the controller, which redirects it to the new_affiliate_registration_path, passing the needed params.
def select_plan
redirect_to new_affiliate_registration_path(plan: plan_params[:button])
end
The new method in the controller is called, directing the user to the sign up page:
# GET /resource/sign_up
def new
#plan = AffiliatePlan.find_by(nickname: params.permit(:plan)[:plan].downcase)
super
end
From this page, if the back button on the browser is selected, it will bring the user back to the page they were at before being at plans.html.erb.
Could this be related to the redirect_to?
EDIT:
Here are the logs:
Started GET "/" for 127.0.0.1 at 2020-02-25 19:06:02 -0500
Processing by Affiliates::RegistrationsController#plans as HTML
Rendering affiliates/registrations/plans.html.erb within layouts/application
Rendered affiliates/registrations/plans.html.erb within layouts/application (5.2ms)
Rendered layouts/_google_analytics.html.erb (0.5ms)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered layouts/_header.html.erb (1.2ms)
Rendered layouts/_footer.html.erb (0.7ms)
Completed 200 OK in 195ms (Views: 194.2ms | ActiveRecord: 0.0ms)
Started POST "/partner/select_plan" for 127.0.0.1 at 2020-02-25 19:06:13 -0500
Processing by Affiliates::RegistrationsController#select_plan as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ck8HGRryriXleQrUjCSKjTrIRLIw273EdSu4WZnFn3kAL1mMmk7jqR1tZgnPniHsMzHFMl81vPBRuvA0/W4uSw==", "button"=>"Local"}
Unpermitted parameters: :utf8, :authenticity_token
Redirected to http://localhost:3000/partners/sign_up?plan=Local
Completed 200 OK in 1ms (ActiveRecord: 0.0ms)
Started GET "/partners/sign_up?plan=Local" for 127.0.0.1 at 2020-02-25 19:06:13 -0500
Processing by Affiliates::RegistrationsController#new as HTML
Parameters: {"plan"=>"Local"}
AffiliatePlan Load (1.2ms) SELECT "affiliate_plans".* FROM "affiliate_plans" WHERE "affiliate_plans"."nickname" = $1 LIMIT $2 [["nickname", "local"], ["LIMIT", 1]]
↳ app/controllers/affiliates/registrations_controller.rb:11
Rendering affiliates/registrations/new.html.erb within layouts/application
Rendered affiliates/registrations/new.html.erb within layouts/application (4.6ms)
Rendered layouts/_google_analytics.html.erb (1.1ms)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered layouts/_header.html.erb (1.2ms)
Rendered layouts/_footer.html.erb (0.7ms)
Completed 200 OK in 191ms (Views: 187.6ms | ActiveRecord: 1.2ms)
I have a hunch that this might have to do with form resubmission: Forms and the back button tend to be a bit wonky at times.
However, instead of going more in depth with this, let me point you in another direction. I'm doing this because to me, this looks like a classic case of someone trying to find a solution to the wrong problem. I'm saying this because based on the code and log snippets you've provided, you're jumping through hoops to pass a parameter (in your case the name of a plan) via multiple actions – which, if I'm right, is just unnecessary.
Here's what I would do instead:
<% #plans.each do |plan| %>
<%=
link_to 'Select Plan',
new_affiliate_registration_path(plan: plan.downcase),
class: 'some-button-class
%>
<% end %>
This way, you don't have to mess around in your controllers in any way. Also, since there is no POST request, you won't have any issues with form (re)population and such things.
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.
So far, to a very experienced Java EE developer with years of experience in many different languages, I am having real difficulties with Ruby on Rails. I am using: ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15] and Rails 5.0.0. I am following a very simple on-line tutorial on building a private library web application, BUT, in order to learn something, instead of having Books with a linked table of Subjects, I changed Subjects to Authors since many books have the same authors. I am using SQLLite for development and MySQL for production( haven't gotten there yet! ). I find that when you follow exactly the directions in most tutorials, you end up with whatever application you were building. But, IF you deviate in any fashion, things just don't work and it's very hard to figure out what happened. You get error messages ( sometimes ) in the logs that you've got an undefined variable or constant. Normally, you would search for where that variable is used, then be sure you define it or spell it correctly. However, in RoR, that constant doesn't appear anywhere except in the log, if there. RoR, due to its conventions, has either created or assumed that you had such a variable, when in fact, you may have named a "view" folder in the singular instead of the plural. It "invented" a variable to point to that, but it didn't match the pattern, so it fails with very poor error messages.
The server doesn't complain, just does a rollback, and goes on. The log has some unmeaningful message, as per above. I end up spending hours trying different patterns for routes suggested by people, or renaming things, but it's all guesswork.
I enjoy working with frameworks and systems where I understand them. This seems to be a collection of different pieces which parse in yml, yaml, erb, rb, sass, haml, etc. I've tried logging, but to no avail. How do you located simple mistakes?
Here is my "books_controller.rb":
class BooksController < ApplicationController
def list
#books = Book.all
end
def show
#book = Book.find(params[:id])
end
def new
#book = Book.new
#authors = Author.all
end
def create
#book = Book.new(book_params)
if #book.save
logger.debug 'Redirecting to list'
redirect_to :action => 'list'
else
#authors = Author.all
render :action => 'new'
end
end
def edit
#book = Book.find(params[:id])
#authors = Author.all
end
def update
#book = Book.find(params[:id])
if #book.update_attributes(book_params)
redirect_to :action => 'show', :id => #book
else
#authors = Author.all
render :action => 'edit'
end
end
def delete
Book.find(params[:id]).destroy
redirect_to :action => 'list'
end
def show_authors
#author = Author.find(params[:id])
end
def book_params
params.require(:books).permit(:title, :description, :author_id)
end
end
The new.html.erb under app/views/books is:
<h1>Add new book</h1>
<%= form_tag :action => 'create' do %>
<p><label for = "book_title">Title</label>:
<%= text_field 'books', 'title' %></p>
<p><label for = "book_author_id">Author</label>:
<%= collection_select(:book, :author_id, #authors, :id, :name, prompt: true) %></p>
<p><label for = "book_description">Description</label><br/>
<%= text_area 'books', 'description' %></p>
<%= submit_tag "Create" %>
<% end -%>
<%= link_to 'Back', {:action => 'list'} %>
routes.rb is:
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :books
#get 'books/list'
#post 'books/create'
#get 'books/new'
#patch 'books/update'
#get 'books/show'
#get 'books/edit'
#get 'books/delete'
get 'books/show_authors'
get 'authors/list'
post 'authors/create'
get 'authors/new'
patch 'authors/update'
get 'authors/show'
get 'authors/edit'
root :to => 'books#list'
end
When I try to add a new book, I enter the title, select an author, and put in a description and click "Create". It then just returns to the new screen. The console has:
Started GET "/books/new" for ::1 at 2016-08-04 17:18:22 -0400
Processing by BooksController#new as HTML
Rendering books/new.html.erb within layouts/application
Author Load (0.1ms) SELECT "authors".* FROM "authors"
Rendered books/new.html.erb within layouts/application (5.4ms)
Completed 200 OK in 26ms (Views: 21.6ms | ActiveRecord: 0.5ms)
Started POST "/books" for ::1 at 2016-08-04 17:18:28 -0400
Processing by BooksController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"noRmEq8rHE6RLs0cPNrlZoQXq//2sr+SAOSHEFc0U3zqbSJZOSKDmdgwpdm5/nVswItHp4Ken0mjggt47ph46Q==", "books"=>{"title"=>"sdfasdf", "description"=>"asdfasdf"}, "book"=>{"author_id"=>"2"}, "commit"=>"Create"}
(0.1ms) begin transaction
(0.1ms) rollback transaction
Rendering books/new.html.erb within layouts/application
Author Load (0.1ms) SELECT "authors".* FROM "authors"
Rendered books/new.html.erb within layouts/application (2.0ms)
Completed 200 OK in 24ms (Views: 20.3ms | ActiveRecord: 0.2ms)
and the development log has:
Started GET "/books/new" for ::1 at 2016-08-04 17:18:22 -0400
Processing by BooksController#new as HTML
Rendering books/new.html.erb within layouts/application
[1m[36mAuthor Load (0.1ms)[0m [1m[34mSELECT "authors".* FROM "authors"[0m
Rendered books/new.html.erb within layouts/application (5.4ms)
Completed 200 OK in 26ms (Views: 21.6ms | ActiveRecord: 0.5ms)
Started POST "/books" for ::1 at 2016-08-04 17:18:28 -0400
Processing by BooksController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"noRmEq8rHE6RLs0cPNrlZoQXq//2sr+SAOSHEFc0U3zqbSJZOSKDmdgwpdm5/nVswItHp4Ken0mjggt47ph46Q==", "books"=>{"title"=>"sdfasdf", "description"=>"asdfasdf"}, "book"=>{"author_id"=>"2"}, "commit"=>"Create"}
[1m[35m (0.1ms)[0m [1m[36mbegin transaction[0m
[1m[35m (0.1ms)[0m [1m[31mrollback transaction[0m
Rendering books/new.html.erb within layouts/application
[1m[36mAuthor Load (0.1ms)[0m [1m[34mSELECT "authors".* FROM "authors"[0m
Rendered books/new.html.erb within layouts/application (2.0ms)
Completed 200 OK in 24ms (Views: 20.3ms | ActiveRecord: 0.2ms)
Yes, the transaction was rolled back. WHY? How can I get information on what caused the database to "rollback"? The two tables in the database are:
class CreateBooks < ActiveRecord::Migration[5.0]
def change
create_table :books do |t|
t.string :title
t.integer :author_id
t.string :description
t.timestamp :created
t.timestamps
end
end
end
class CreateAuthors < ActiveRecord::Migration[5.0]
def change
create_table :authors do |t|
t.string :name
t.timestamps
end
end
end
class Book < ApplicationRecord
belongs_to :author
validates_presence_of :title
end
class Author < ApplicationRecord
has_many :books
end
I can create a book in rails console as:
b=Book.create :title=>'Test', :author_id=>1, :description=>'Desc'
(0.1ms) begin transaction
Author Load (0.1ms) SELECT "authors".* FROM "authors" WHERE "authors"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
SQL (0.3ms) INSERT INTO "books" ("title", "author_id", "description", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["title", "Test"], ["author_id", 1], ["description", "Desc"], ["created_at", 2016-08-04 20:17:40 UTC], ["updated_at", 2016-08-04 20:17:40 UTC]]
(2.4ms) commit transaction
=> #<Book id: 1, title: "Test", author_id: 1, description: "Desc", created: nil, created_at: "2016-08-04 20:17:40", updated_at: "2016-08-04 20:17:40">
I would appreciate input and especially help on understanding why what happened actually happened. It seems that a very simple error is being made, but I can't see it.
------------------ Added after several answers and "guesses" by me.
I changed the form_tag to a form_for as I'll show below.
----new.html.erb------
<%= form_for(#book) do |f| %>
Title: <%= f.text_field :title %><br/>
Author: <%= select("book", "author_id", Author.all.collect{|p| [p.name,p.id]}, prompt: 'Select') %><br/>
Description: <%= f.text_area :description %><br/>
<%= f.submit "Create" %>
<% end -%>
<%= link_to 'Back', {:action => 'list'} %>
I get in the browser:
Validation failed: Author must exist, Title can't be blank
Extracted source (around line #18):
16
17
18
19
20
21
def create
#book = Book.new
if #book.save!
redirect_to :action => 'list'
else
#authors = Author.all
Rails.root: /Users/woo/Development/rails/library
Application Trace | Framework Trace | Full Trace
app/controllers/books_controller.rb:18:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"gi+wVGV3MIlkJsRjO8Ig1cS3YV/OIADSevFJg7ItBesokIiHFDThycTO8/kob+2E1fuPFquFUK+b7bGksWRZGQ==",
"book"=>{"title"=>"Book", "author_id"=>"2", "description"=>"test"},
"commit"=>"Create"}
As far as I can see, book does have a title, and an author_id, and a description. Why "Author must exist, Title can't be blank"?
Try using form_for instead of form_tag in your books/new view. This is the Rails way to create forms for model object.
Check a handy guide on form_for here.
How to debug ....
There are several tools to help debug a Rails application. One you have already discovered: the log file in log/development.log.
Another is Byebug. Add the gem to your Gemfile and insert the following in the create action after the 'else':
require 'byebug'
byebug
then post the form again. The development server will bring up a Byebug console where you can inspect local variables, instance variables, and the stack trace. Try inspecting:
#book.errors
When an ActiveRecord model fails to save it is usually because validations failed. Errors encountered when saving are added to the errors object on the model instance.
The reason for the failure is probably that the form is not passing the expected parameters. By convention, Rails expects attributes for the model to be in a hash where the key is the model name, so params[:book][:title], not params[:title]. See the documentation for the form_for helper for more info.
Thanks for the help. With your suggestions and a lot of guessing from ready various Google sites, I combined them and in the new.html.erb put form_for(#book), and then in the create method of books_controller.rb, I put #book - Book.new(book_params), where book_params is:
def book_params
params.require(:book).permit(:title, :author_id, :description)
end
I'm guessing that this is to handle the strong attribution required by Rails 4 and up. Before I had books as the first argument and since it existed, but book was not filled, I got the weird error. After using form_for with #book as an argument, that set the values from the form into the book hash. Then the params.require with :book as the first argument, looked in that hash to extract title, author_id, and description.
Again, many thanks for the help and I learned about bye bug and save! and so forth. I find information is very sketchy and ofter the version is not mentioned, thus leading one astray many times.
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')
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'