Im a rails beginner on Rails 4. Im trying to create a wine list that takes the name of the winery and the year of the bottle. Here is my form
<%= form_for #wine do |f| %>
<%# render "errors", object: #wine %>
<div class="form-group input-group input-group-lg">
<%= f.text_field :name, placeholder: "Enter the winery name", class: "form-control input-lg" %>
</div>
<div class="form-group input-group input-group-lg">
<%= select_year(Date.today, start_year: Time.now.year, end_year: Time.now.year - 90, field_name: :year, prefix: :wine) %>
</div>
<div class="form_group input-group">
<%= f.submit "Add wine", class: "btn btn-success" %>
</div>
<% end %>
Here is my controller
class WinesController < ApplicationController
before_action :set_wine, only: [:show, :edit, :update, :destroy]
def index
#wines = Wine.all
end
def new
#wine = Wine.new
end
def create
#wine = Wine.new(wine_params)
if #wine.save
flash[:notice] = "Successfully created..."
redirect_to #wine
else
flash.now[:error] = "There was a problem"
render "new"
end
end
def show
end
def edit
end
def update
if #wine.update(wine_params)
redirect_to #wine
else
flash[:error] = "Something went wrong"
render "edit"
end
end
def destroy
#wine.destroy
redirect_to wines_path
end
private
def set_wine
#wine = Wine.find(params[:id])
end
def wine_params
params.require(:wine).permit(:name, :year)
end
end
I have my wines table with a name:string column and a year:datetime column
Whenever I try and create a new wine I get an argument out of range exception and it highlights #wine = Wine.new(wine_params) in my create action. What am I doing wrong?
My log
Started GET "/wines/new" for 127.0.0.1 at 2013-09-04 10:55:54 -0700
Processing by WinesController#new as HTML
Rendered wines/_form.html.erb (2.0ms)
Rendered wines/new.html.erb within layouts/application (2.6ms)
Rendered layouts/_header.html.erb (0.2ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 10ms (Views: 9.3ms | ActiveRecord: 0.0ms)
Started GET "/assets/comingsoonbg.png" for 127.0.0.1 at 2013-09-04 10:55:54 -0700
Started GET "/wines/new" for 127.0.0.1 at 2013-09-04 10:55:54 -0700
Processing by WinesController#new as HTML
Rendered wines/_form.html.erb (2.1ms)
Rendered wines/new.html.erb within layouts/application (2.7ms)
Rendered layouts/_header.html.erb (0.2ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 10ms (Views: 9.8ms | ActiveRecord: 0.0ms)
Started POST "/wines" for 127.0.0.1 at 2013-09-04 10:55:59 -0700
Processing by WinesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"FCd3wvCov+mugnJuzwplKD/eVskJKgxweh1mK0pG2wM=", "wine"=>{"name"=>"kjkljhk", "year"=>"2013"}, "commit"=>"Add wine"}
Completed 500 Internal Server Error in 1ms
ArgumentError (argument out of range):
app/controllers/wines_controller.rb:13:in `create'
Rendered /Users/me/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.7ms)
Rendered /Users/me/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.9ms)
Rendered /Users/me/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.9ms)
Rendered /Users/me/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (16.2ms)
My schema for wines in schema.rb
create_table "wines", force: true do |t|
t.datetime "year"
t.datetime "created_at"
t.datetime "updated_at"
t.string "name"
end
Date and Time always require me to think twice! In the log, params contains a string with the year from the select_year. The simplest solution was to just store the integer representation, if all you'll need are years. If you later change to select_date, you'll need to build a Date object in your controller by extracting the parts from the params hash. See Form Helpers Guide for more detail... well, here is just a bit.
In the view:
<%= select_date Date.today, prefix: :start_date %>
In the controller, to make your Date object:
Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i)
ActiveRecord expects an attribute to have one entry in the params hash, but Date objects require multiple values. The date helper date_select (not select_date) will pass back a hash that Rails will convert, with multiparameter assignment, to a Date during mass assignment.
<%= date_select :person, :birth_date %>
If you used date_select, you's see something like this in the params hash:
{:person => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}}
Notice the keys in the :person hash describe the order and type of the multipart object so that Rails can figure out how to create the attribute (for example, the hash key birth_date(2i) is the second component of the birth_date attribute in a Person model object and is an integer).
Related
I wanted to display my time variables to see when pass has started and when will it end but don't know how and couldn't find solution.
I tried something very simple but it doesn't work:
show.html.erb
<h1><%= #pass.name %></h1>
<p><%= #pass.valid_from %></p>
<p><%= #pass.valid_until %></p>
create_passes.rb migration
class CreatePasses < ActiveRecord::Migration[7.0]
def change
create_table :passes do |t|
t.time :valid_from
t.time :valid_until
t.boolean :is_time_limited
t.integer :entries_left
t.string :name
t.timestamps
end
end
end
passes_controller.rb
class PassesController < ApplicationController
def index
#passes = Pass.all
end
def show
#pass = Pass.find(params[:id])
end
def new
#pass = Pass.new
end
def create
#pass = Pass.new(pass_params)
if #pass.save
redirect_to #pass
else
render :new, status: :unprocessable_entity
end
end
def edit
#pass = Pass.find(params[:id])
end
def update
#pass = Pass.find(params[:id])
if #pass.update(pass_params)
redirect_to #pass
else
render :edit, status: :unprocessable_entity
end
end
def destroy
#pass = Pass.find(params[:id])
#pass.destroy
redirect_to root_path, status: :see_other
end
private
def pass_params
params.require(:pass).permit(:name, :is_time_limited, :valid_from, :valid_until, :entries_left)
end
end
new/edit pass form view
<%= form_with model: #pass do |form| %>
<div>
<%= form.label :name %><br>
<%= form.text_field :name %>
<% #pass.errors.full_messages_for(:name).each do |message| %>
<div><%= message %></div>
<% end %>
</div>
<div>
<%= form.label :valid_from %><br>
<%= form.date_field :valid_from %>
<% #pass.errors.full_messages_for(:name).each do |message| %>
<div><%= message %></div>
<% end %>
</div>
<div>
<%= form.label :valid_until %><br>
<%= form.date_field :valid_until %>
<% #pass.errors.full_messages_for(:name).each do |message| %>
<div><%= message %></div>
<% end %>
</div>
<div>
<%= form.submit %>
</div>
<% end %>
rails server log
Started GET "/passes/2" for ::1 at 2022-08-10 18:18:18 +0200
Processing by PassesController#show as HTML
Parameters: {"id"=>"2"}
(0.1ms) SELECT sqlite_version(*)
↳ app/controllers/passes_controller.rb:7:in `show'
Pass Load (0.2ms) SELECT "passes".* FROM "passes" WHERE "passes"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
↳ app/controllers/passes_controller.rb:7:in `show'
Rendering layout layouts/application.html.erb
Rendering passes/show.html.erb within layouts/application
Rendered layouts/_navbar.html.erb (Duration: 1.0ms | Allocations: 724)
Rendered passes/show.html.erb within layouts/application (Duration: 2.8ms | Allocations: 1670)
Rendered layout layouts/application.html.erb (Duration: 6.9ms | Allocations: 4039)
Completed 200 OK in 31ms (Views: 7.5ms | ActiveRecord: 0.5ms | Allocations: 5333)
Also, is it better to use time or datatime type for dates and time?
Ok I believe I know why you are not getting any values.
You setup your DB to use a time field
t.time :valid_from
t.time :valid_until
But you are using a date_field in the view:
form.date_field :valid_from
You need to change this to:
form.time_field :valid_from
The difference between time or datetime is datetime includes a DATE and a TIME, where TIME ONLY has a time so it depends on what your use case is. You can also use just a date and then it would be
form.date_field :valid_from
If you need dates you will need to change your model and DB to use either t.date or t.datetime. If you don't have a lot of information in your DB you can do a rails db:rollback and modify your migration file would be the quickest and easiest way to fix it. IF you DO have data you will have to create a new migration to change the fields.
TL;DR Why does my user sign in form not create a new session/why does it fail without errors?
I'm pretty new to rails, and I'm having some confusion about user sign in forms that create new sessions. Essentially I can either sign the user in without creating a session, or signing in doesn't work and also doesn't create the session, but I don't get any errors.
I have tried:
Using whatever versions of form_with I can find, as well as form_for and form_tag.
Changing routes to anything and everything I can find in google.
Setting SameSite="Lax".
new.html.erb
<h1>This is the new viewer page!</h1>
<%= form_with model: #user do |f| %>
<%= f.label :name %>
<%= f.text_field :name %><br>
<%= f.label :username %>
<%= f.text_field :username %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.text_field :password %>
<%= f.submit %>
<% end %>
<%= form_for :session, url: login_path do |f| %>
<%= f.label :id %>
<%= f.text_field :id %>
<%= f.submit "Sign in" %>
<% end %>
sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
#user = User.find_by_id(params[:id])
if #user && #user.authenticate(params[:id][:password_digest])
session[:id] = #user.id
redirect_to user_path(#user), notice: "User logged in"
else
redirect_to root_path, alert: "Something is wrong"
end
end
def destroy
session[:user_id] = nil
redirect_to root_path
end
end
routes.rb
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :users
resources :sessions
get "/login", to: "sessions#new"
post "/login", to: "sessions#create", via: :"post"
delete "/logout", to: "sessions#destroy"
root "users#new"
end
I'm aware that my flash message is useless for debugging, I also couldn't find anything straightforward on getting clearer debug output. the only thing I can find is a warning in the browser console talking about samesite=none so cookies will be rejected (i'm using firefox)
EDIT
The log when I try to submit the form
Started POST "/login" for 127.0.0.1 at 2021-01-22 01:01:56 -0500
Processing by SessionsController#create as HTML
Parameters: {"authenticity_token"=>"uUeDMYJKaxduZGqKJvaDiSO1bCFYDSIz6dcmp6CEeUNTYwBycJUb5l10K5KXcPZG2kOgdiK6pvPAKoDexwqSmA==", "session"=>{"id"=>"12"}, "commit"=>"Sign in"}
[1m[36mUser Load (0.4ms)[0m [1m[34mSELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ?[0m [["LIMIT", 1]]
↳ app/controllers/sessions_controller.rb:6:in `create'
Redirected to http://localhost:3000/
Completed 302 Found in 14ms (ActiveRecord: 0.4ms | Allocations: 1013)
Started GET "/" for 127.0.0.1 at 2021-01-22 01:01:56 -0500
Processing by UsersController#new as HTML
Rendering users/new.html.erb within layouts/application
Rendered users/new.html.erb within layouts/application (Duration: 2.3ms | Allocations: 1302)
[Webpacker] Everything's up-to-date. Nothing to do
Completed 200 OK in 9ms (Views: 8.7ms | ActiveRecord: 0.0ms | Allocations: 4667)
EDIT 2
log after making some changes:
Started POST "/users" for 127.0.0.1 at 2021-01-23 03:22:03 -0500
Processing by UsersController#create as JS
Parameters: {"authenticity_token"=>"TIbECQO9vWQfDfmT89rGHKtdlamLXOUG3MYVgiB1bqZJJgp8C0h9LmFdyrLOS4HTmi/IHBp5bz0flz7BRU5wYA==", "user"=>{"id"=>"12"}, "commit"=>"Sign in"}
Redirected to http://localhost:3000/users/12
Completed 200 OK in 9ms (ActiveRecord: 0.0ms | Allocations: 2142)
Started GET "/users/12" for 127.0.0.1 at 2021-01-23 03:22:03 -0500
Processing by UsersController#show as HTML
Parameters: {"id"=>"12"}
[1m[36mUser Load (0.3ms)[0m [1m[34mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?[0m [["id", 12], ["LIMIT", 1]]
↳ app/controllers/users_controller.rb:3:in `show'
Rendering users/show.html.erb within layouts/application
Rendered users/show.html.erb within layouts/application (Duration: 1.3ms | Allocations: 96)
[Webpacker] Everything's up-to-date. Nothing to do
Completed 200 OK in 12ms (Views: 8.1ms | ActiveRecord: 0.3ms | Allocations: 4300)
The reason nothing is happening is that the code is completely broken.
Look at the parameters in the log:
Processing by UsersController#create as JS
Parameters: {"authenticity_token"=>"TIbECQO9vWQfDfmT89rGHKtdlamLXOUG3MYVgiB1bqZJJgp8C0h9LmFdyrLOS4HTmi/IHBp5bz0flz7BRU5wYA==", "user"=>{"id"=>"12"}, "commit"=>"Sign in"}
Now look at your create method:
def create
#user = User.find_by_id(params[:id])
if #user && #user.authenticate(params[:id][:password_digest])
session[:id] = #user.id
redirect_to user_path(#user), notice: "User logged in"
else
redirect_to root_path, alert: "Something is wrong"
end
end
There is no params[:id] nor any password passed anywhere in the parameters. params[:id][:password_digest] is also always going to be nil. So if #user && #user.authenticate(params[:id][:password_digest]) is NEVER going to be true.
params[:id][:password_digest] is straight up bonkers as you generate password digests with a encryption algorithm like bcrypt from a plain-text password and save it in the database. Never would you actually take a password digest from a user.
Instead when signing a user in you take a plain-text password and pass that to bcrypt which tells you if the password digest matches any of the hashes generated for that string. If it does .authenticate returns true.
Having the user supply and id instead of something like an email or username is also strange.
What you actually want is something like:
class User < ApplicationRecord
has_secure_password
end
class SessionsController < ApplicationController
# GET /login
def new; end
# POST /login
def create
#user = User.find_by_email(params[:email])
if #user&.autenticate(params[:password])
session[:user_id] = #user.id
else
flash.now[:error] = 'Invalid email or password'
render :new
end
end
# DELETE /logout
def destroy
session.delete(:user_id)
redirect_to root_path
end
end
# app/views/sessions/_form.html.erb
# this creates a form with "unnested" inputs
<%= form_with url: login_path, local: true do |form| %>
<div class="field">
<%= f.label :email %>
<%= f.email_field :email %>
</div>
<div class="field">
<%= f.label :password %>
<%= f.password_field :email %>
</div>
<%= f.submit "Sign in" %>
<% end %>
# app/views/sessions/new.html.erb
<h1>Sign in</h1>
<%= render partial: 'form' %>
I am trying to create two objects from one nested form in Rails, recipe which has_many :ingredients.
When I submit the form, Rails returns an error:
undefined method `ingredient' for #<Ingredient id: nil, ing: "a", amount: "a", recipe_id: nil> Did you mean? increment
Specifically pointing out the error in my create action:
#recipe = Recipe.new(recipe_params)
# #recipe.user_id = session[:user_id]
#recipe.save
redirect_to recipe_path(#recipe)
end
I suspect my problem is in model associations.
Full trace:
Started POST "/recipes" for ::1 at 2016-12-19 13:53:06 -0600
Processing by RecipesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"wmdURAmdmdHrbrW3+0z5MvEIOs7hY5QBfzKG/L1PSgFKJPRHbFQlGMpBYeIwYdnRxPprsEKk1HT7qQNbSOo42Q==",
"recipe"=>{"name"=>"adsfadsfa",
"steps"=>"a",
"ingredients_attributes"=>{"0"=>{"ing"=>"a", "amount"=>"a"}}},
"commit"=>"Add"}
ActionController::Parameters {"name"=>"adsfadsfa",
"steps"=>"a",
"ingredients_attributes"=>
<ActionController::Parameters
{"0"=><ActionController::Parameters
{"ing"=>"a", "amount"=>"a"} permitted: true>} permitted: true>} permitted: true>
(0.1ms) begin transaction
(0.1ms) rollback transaction
Completed 500 Internal Server Error in 47ms (ActiveRecord: 0.3ms)
app/controllers/recipes_controller.rb:13:in `create'
Rendering /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
Rendering /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
Rendered /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (11.0ms)
Rendering /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
Rendered /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (5.6ms)
Rendering /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (3.6ms)
Rendered /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (153.7ms)
Rendering /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/index.html.erb
Rendered /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/_markup.html.erb (1.0ms)
Rendering /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/console.js.erb within layouts/javascript
Rendering /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string
Rendered /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.9ms)
Rendering /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string
Rendered /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (1.0ms)
Rendering /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/style.css.erb within layouts/inlined_string
Rendered /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/style.css.erb within layouts/inlined_string (1.0ms)
Rendered /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/console.js.erb within layouts/javascript (116.1ms)
Rendering /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/main.js.erb within layouts/javascript
Rendered /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/main.js.erb within layouts/javascript (0.9ms)
Rendered /Users/JCamp1991/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/index.html.erb (229.6ms)
recipes_controller.rb:
...
def create
#recipe = Recipe.new(recipe_params)
#recipe.user_id = session[:user_id]
#recipe.save
redirect_to recipe_path(#recipe)
end
...
def recipe_params
params.require(:recipe).permit(:name, :steps, ingredients_attributes: [:ing, :amount])
end
Models:
class Ingredient < ApplicationRecord
belongs_to :recipe
...
end
class Recipe < ApplicationRecord
...
has_many :ingredients
accepts_nested_attributes_for :ingredients
validates_associated :ingredients
...
end
New recipe form:
<%= form_for #recipe do |f| %>
<h1>
<%= f.label :name %><br>
<%= f.text_field :name %><br>
</h1>
<h1>
<%= f.label :steps %><br>
<%= f.text_area :steps %><br>
</h1>
<%= f.fields_for :ingredients do |p| %>
<h1>
<%= p.label :ing %><br>
<%= p.text_area :ing %><br>
</h1>
<h1>
<%= p.label :amount %><br>
<%= p.text_area :amount %><br>
</h1>
<% end %>
<%= f.submit "Add" %><br>
Included in routes.rb:
resources :users do
resources :recipes
end
resources :recipes do
resources :ingredients
end
Github Repo for entire project:
https://github.com/jlcampbell1991/recipe-box
Ingredient model probably shouldn't have an ingredient attribute. What about name?
It also doesn't seem to be consistent between migrations
t.string :ing
and Model :
validates :ingredient, presence: true
I am getting an error in my rails application. param is missing or the value is empty: contact
Home Controller
def contact
#contact = Contact.new(contact_params)
if #contact.save
redirect_to root_path
firstname = params[:contact][:firstname]
lastname = params[:contact][:lastname]
email = params[:contact][:email]
message = params[:contact][:message]
ContactMailer.contact_email(firstname, lastname, email, message).deliver
flash[:success] = "Thanks for your message, we will be in touch soon."
else
redirect_to home_contact_path
flash[:danger] = "Opps, there was a problem! Please fill out all the fields."
end
end
private
def contact_params
params.require(:contact).permit(:firstname, :lastname, :email, :message)
end
Mailer/Form
<div class="contact-form">
<%= simple_form_for #contact do |f| %>
<%= f.input :firstname, required: true %>
<%= f.input :lastname, required: true %>
<%= f.input :email, required: true %>
<%= f.input :message, required: true %>
<%= f.submit "Get in touch!", class: "btn btn-info" %>
<% end %>
</div>
Contact Page
<!DOCTYPE html>
<div class="jumbotron">
<h1 class="center-aligned">Contact Me</h1>
</div>
<div class="main-content">
<p class="center-aligned">You can contact me via the social media links at the bottom of the site or via the contact form below.</p>
<%= render 'home/mailer' %>
</div>
Contact.rb
class Contact < ActiveRecord::Base
validates_presence_of :firstname, :lastname, :email, :message
end
Server Log
Started GET "/home/contact" for 127.0.0.1 at 2016-05-17 14:13:13 -0500
Processing by HomeController#contact as HTML
Completed 500 in 6ms (ActiveRecord: 0.0ms)
ActionController::ParameterMissing (param is missing or the value is empty: contact):
app/controllers/home_controller.rb:28:in `contact_params'
app/controllers/home_controller.rb:9:in `contact'
Rendered /home/andy/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_source.erb (21.9ms)
Rendered /home/andy/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (9.8ms)
Rendered /home/andy/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (3.5ms)
Rendered /home/andy/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (80.8ms)
Rendered /home/andy/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (1.9ms)
Rendered /home/andy/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (1.3ms)
Rendered /home/andy/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (1.8ms)
Rendered /home/andy/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (1.9ms)
Rendered /home/andy/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (72.9ms)
Rendered /home/andy/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (1.3ms)
Rendered /home/andy/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (2.0ms)
Rendered /home/andy/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (135.5ms)
Please let me know if you need anything else. I am still learning Ruby on Rails.
You're not defining #contact when you render the form.
The action that renders the form need a code similar like #contact = Contact.new
On the other hand, you need to define a POST method for submit the form. Contact should be your post method where the form is submited and you need another action GET with the code that I give you before.
def contact
#contact = Contact.new(contact_params)
end
def create
if #contact.save
redirect_to root_path
firstname = params[:contact][:firstname]
lastname = params[:contact][:lastname]
email = params[:contact][:email]
message = params[:contact][:message]
ContactMailer.contact_email(firstname, lastname, email, message).deliver
flash[:success] = "Thanks for your message, we will be in touch soon."
else
redirect_to home_contact_path
flash[:danger] = "Opps, there was a problem! Please fill out all the fields."
end
end
routes.rb
resources :contacts
Simply your form parameter is empty, reason of getting the error from there. Also, you have to define your routes.
Form
<%= simple_form_for Contact.new, url: :contact_emailer do |f| %>
routes
post 'contact_emailer' => "contacts#contact", as: :contact_emailer
You get this error because you try to assign params here:
#contact = Contact.new(contact_params)
and since nothing has been submitted yet, and you specified that params.require(:contact) you get the error.
Here's what you do: as a good rails citizen create separate method for showing the form (usually new) and another one for submitting it (usually create)
It would look little bit like this:
def new
#contact = Contact.new # this is empty model, no data yet
end
def create
#contact = Contact.new(contact_params)
# ... and all the other fancy stuff you have there
end
don't forget to update your view filename to new.html.erb or call render in the controller.
It is possible to use one method to both show new form and handle request on submit but the separation to new/create is more clear.
I don't know why this is happening. Can anyone explain why I am getting wrong number of arguments for this search? I am just doing a search where you have two fields for the search subject and zip. But when i run the search I get the wrong number of argument error.
Model:
class Profile < ActiveRecord::Base
has_and_belongs_to_many :subjects
belongs_to :user
geocoded_by :zip
after_validation :geocode, :if => :zip_changed?
searchable do
text :subject_search
latlon(:location) { Sunspot::Util::Coordinates.new(self.latitude, self.longitude) }
string :search_near
end
def search_near
self.zip
end
def subject_search
subjects.map { |subject| subject.title }
end
end
Controller:
def index
#search = Profile.search do
fulltext params[:subject_search]
with(:location).in_radius(*Geocoder.coordinates(params[:search_near]), 10)
if params[:search_near].present?
end
#profiles = #search.results
end
View:
<%= form_tag profiles_path, method: :get do %>
<p>Enter Zip:</p>
<%= text_field_tag :search_near, params[:search_near] %>
<p>Enter Subject:</p>
<%= text_field_tag :subject_search, params[:subject_search] %>
<%= submit_tag "Search", name: nil %>
</p>
<% end %>
Started GET "/profiles?utf8=%E2%9C%93&search_near=33029&subject_search=English+1" for ::1 at 2015-06-26 15:53:28 -0400
Processing by ProfilesController#index as HTML
Parameters: {"utf8"=>"✓", "search_near"=>"33029", "subject_search"=>"English 1"}
Geocoding API not responding fast enough (use Geocoder.configure(:timeout => ...) to set limit).
Completed 500 Internal Server Error in 3010ms
ArgumentError (wrong number of arguments (1 for 3..4)):
app/controllers/profiles_controller.rb:8:in block in index'
app/controllers/profiles_controller.rb:6:inindex'
Rendered /Users/mikinad/.rvm/gems/ruby-2.1.1/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_source.erb (9.1ms)
Rendered /Users/mikinad/.rvm/gems/ruby-2.1.1/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_trace.html.erb (3.5ms)
Rendered /Users/mikinad/.rvm/gems/ruby-2.1.1/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_request_and_response.html.erb (1.3ms)
Rendered /Users/mikinad/.rvm/gems/ruby-2.1.1/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/_web_console.html.erb (1.4ms)
Rendered /Users/mikinad/.rvm/gems/ruby-2.1.1/gems/web-console-2.0.0/lib/action_dispatch/templates/rescues/diagnostics.html.erb within rescues/layout (60.8ms)