How to display date variables on site using Ruby on Rails? - ruby-on-rails

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.

Related

Rendering a nested partial template - to rended a nested form on a two separate models

I'm on week two of this issue and have recently used the railsCast #196 (revised). I know this is older - maybe that's my issue. As an extra spin I'm hosting my rails server off Cloud 9.
I've tried following a few different tutorials just to get one going & this is as far as I've gotten. The weird part is none of their syntex matches what the official ruby on rails documentation has ... Rails View templates.
In the railsCast the guy is able to get blank fields to show up ... I'm not sure how...so I haven't managed to populate the question or answer fields yet. I'm not even sure what the two rails console messages mean - besides there aren't records there to be had.
Thanks for reading & any suggestions!
-M
Without further ado, my senario ... nested forms via templates as shown in railsCast 196 ...
My rails console ...
2.2.1 :045 > cc = Survey.first.questions.first
Survey Load (0.5ms) SELECT "surveys".* FROM "surveys" ORDER BY "surveys"."id" ASC LIMIT 1
Question Load (0.2ms) SELECT "questions".* FROM "questions" WHERE "questions"."survey_id" = ? ORDER BY "questions"."id" ASC LIMIT 1 [["survey_id", 1]]
=> nil
2.2.1 :046 > cc = Survey.first.questions
Survey Load (0.3ms) SELECT "surveys".* FROM "surveys" ORDER BY "surveys"."id" ASC LIMIT 1
Question Load (0.2ms) SELECT "questions".* FROM "questions" WHERE "questions"."survey_id" = ? [["survey_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy []>
My terminal console log ...
Started GET "/surveys/5/edit" for 68.54.21.200 at 2015-11-27 02:46:48 +0000
Cannot render console from 68.54.21.200! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by SurveysController#edit as HTML
Parameters: {"id"=>"5"}
Survey Load (0.4ms) SELECT "surveys".* FROM "surveys" WHERE "surveys"."id" = ? LIMIT 1 [["id", 5]]
Question Load (0.2ms) SELECT "questions".* FROM "questions" WHERE "questions"."survey_id" = ? [["survey_id", 5]]
Rendered surveys/_form.html.erb (4.2ms)
Rendered surveys/edit.html.erb within layouts/application (7.3ms)
Completed 200 OK in 70ms (Views: 67.9ms | ActiveRecord: 0.5ms)
So my code ...
surveys_controller.rb
class SurveysController < ApplicationController
def index
#surveys = Survey.all
end
def show
#survey = Survey.find(params[:id])
end
def new
#survey = Survey.new
3.times do
question = #survey.questions.build
4.times { question.answers.build }
end
end
def create
#survey = Survey.new(survey_params)
if #survey.save
flash[:notice] = "Successfully created survey."
redirect_to #survey
else
render :action => 'new'
end
end
def edit
#survey = Survey.find(params[:id])
end
def update
#survey = Survey.find(params[:id])
if #survey.update_attributes(params[:survey])
flash[:notice] = "Successfully updated survey."
redirect_to #survey
else
render :action => 'edit'
end
end
def destroy
#survey = Survey.find(params[:id])
#survey.destroy
flash[:notice] = "Successfully destroyed survey."
redirect_to surveys_url
end
private
def survey_params
params.required(:survey).permit(:id, :survey, :notice)
end
end
Edit action view
<% title = "Edit Survey" %>
<%= render 'form' %>
<p>
<%= link_to "Show", #survey %> |
<%= link_to "View All", surveys_path %>
</p>
_form.html.erb
<%= form_for(#survey) do |f| %>
<% if #survey.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#survey.errors.count, "error") %> prohibited this survey from being saved:</h2>
<ul>
<% #survey.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<% f.fields_for :questions do |builder| %>
<%= render "question_fields", :f => builder %>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
_question_fields.html.erb
<p>
<%= f.label :content, "Question" %><br />
<%= f.text_area :content, :rows => 3 %><br />
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remove Question" %>
</p>
<% f.fields_for :answers do |builder| %>
<%= render 'answer_fields', :f => builder %>
<% end %>
_answer_fields.html.erb
<p>
<%= f.label :content, "Answer" %>
<%= f.text_field :content %>
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remove" %>
</p>
In each of the 7 projects I ran off the web...
It was the nesting of the array's within the params.require() that was the problem.. It's one thing to tell someone it has to be nested - it's another to show them the syntax when they are new :)
Example:
// Note this is from memory, as I deleted this version of the github..so it's not exactly right or tested...
params.require(:survey).permit(:id,:questions => [:id, :survey_id, :question, :answers => [:id, :question_id, :answer]])
Here's the break down of that same example in depth:
params.require(:survey).permit(
:id,
:questions => [:id, // This is the 1st nesting
:survey_id, :question, :answers => [:id, // This is 1st nested array ":questions"
:question_id, :answer] // End the 2nd nested array ":answers"
] // End the 2nd array ":questions"
) // End the ":surveys" array & the .permit as a whole

Why is my name method undefined?

I am receiving a undefined method `name' for # error for my Rails project. I know that name is defined for events by double checking using my console, so I don't understand why it won't load. Here is some of my code:
Apps Show:
<h1><%= #app.title %></h1>
<h5>App URL: <%= #app.url %></h5>
<h5>App User_id: <%= #app.user_id %></h5>
<br>
<h2> Events </h2>
<% #events.each do |event| %>
<div>
<%= event.name %><span class="badge"><%= event.count %></span>
</div>
<% end %>
<br>
<%= link_to "Edit", edit_app_path(#app), class: 'btn btn-success' %>
Apps Controller:
class AppsController < ApplicationController
def create
#app = App.new(params.require(:app).permit(:title, :url))
#app.user_id = 1
if #app.save
flash[:notice] = "App was saved!"
redirect_to #app
else
flash[:error] = "There an error, oh noes!Please try again!"
render :new
end
end
def new
#app = App.new
end
def show
#app = App.find(params[:id])
#events = #app.events.group_by(&:name)
end
def index
#apps = App.all
end
def edit
#app = App.find(params[:id])
end
def update
#app = App.find(params[:id])
if #app.update_attributes(params.require(:app).permit(:title, :url))
flash[:notice] = "Application was updated."
redirect_to #app
else
flash[:error] = "There was an error saving the app. Please try again."
render :edit
end
end
def destroy
#app = App.find(params[:id])
if #app.destroy
flash[:notice] = "App was removed."
redirect_to #app
else
flash[:error] = "App couldn't be deleted. Try again."
redirect_to #app
end
respond_to do |format|
format.html
format.js
end
end
end
Events Seed:
create_table "events", force: :cascade do |t|
t.integer "app_id"
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
App Model:
class App < ActiveRecord::Base
belongs_to :user
has_many :events
end
Complete Error Log:
Completed 500 Internal Server Error in 19ms
ActionView::Template::Error (undefined method `name' for #<Array:0x007fcc53394af0>):
6: <h2> Events </h2>
7: <% #events.each do |event| %>
8: <div>
9: <%= event.name %><span class="badge"><%= event.count %></span>
10: </div>
11: <% end %>
12: <br>
app/views/apps/show.html.erb:9:in `block in _app_views_apps_show_html_erb__2949113196422864311_70257764571040'
app/views/apps/show.html.erb:7:in `each'
app/views/apps/show.html.erb:7:in `_app_views_apps_show_html_erb__2949113196422864311_70257764571040'
Rendered /Users/ericpark/.rvm/gems/ruby-2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_source.erb (7.1ms)
Rendered /Users/ericpark/.rvm/gems/ruby-2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (4.1ms)
Rendered /Users/ericpark/.rvm/gems/ruby-2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.9ms)
Rendered /Users/ericpark/.rvm/gems/ruby-2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout (71.2ms)
Rendered /Users/ericpark/.rvm/gems/ruby-2.2.0/gems/web-console-2.1.3/lib/web_console/templates/_markup.html.erb (0.7ms)
Rendered /Users/ericpark/.rvm/gems/ruby-2.2.0/gems/web-console-2.1.3/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.7ms)
Rendered /Users/ericpark/.rvm/gems/ruby-2.2.0/gems/web-console-2.1.3/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.5ms)
Rendered /Users/ericpark/.rvm/gems/ruby-2.2.0/gems/web-console-2.1.3/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.3ms)
Rendered /Users/ericpark/.rvm/gems/ruby-2.2.0/gems/web-console-2.1.3/lib/web_console/templates/console.js.erb within layouts/javascript (69.6ms)
Rendered /Users/ericpark/.rvm/gems/ruby-2.2.0/gems/web-console-2.1.3/lib/web_console/templates/main.js.erb within layouts/javascript (0.4ms)
Rendered /Users/ericpark/.rvm/gems/ruby-2.2.0/gems/web-console-2.1.3/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.7ms)
Rendered /Users/ericpark/.rvm/gems/ruby-2.2.0/gems/web-console-2.1.3/lib/web_console/templates/index.html.erb (156.5ms)
#events is hash you have to iterate like
<% #events.each do |event| %>
<div>
<%= event[0] %><span class="badge"><%= event[1].count %></span>
</div>
<% end %>
In cases like this, simple debug printing will reveal the problem. Is name not defined on #events when you think it should be? Are you sure that #events is what you think it is?
Add p #events line to your controller, retry the request and read the log. A piece of advice for the future. :)
The problem starts here:
#events = #app.events.group_by(&:name)
I'm pretty sure that output of group_by is a hash, where keys are different names and values are arrays of events which all have the same name. (depends on what exactly the implementation of group_by is, of course)
<% #events.each do |event| %>
event here is not an instance of Event class, but a two element array, [name, [event1, event2, ...]]. You should iterate this nested array to get real events, which do have the method you want.
<% #events.each do |name, events| %>
<%= name %> <%= events.length %>

Rails 4 not inserting values into database

I'm working on a small demo app to help myself understand how to implement cascading selects on Rails 4, but I've run into an interesting problem:
When I fill out a form and submit it to the database, the parameters seem to be passed, but the values are not being saved in the database because the SQL skips the field names and values, as demonstrated in this snippet from the console:
Started POST "/prop_sub_types" for ::1 at 2015-01-23 18:54:05 -0800
Processing by PropSubTypesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"7mGqF/MR+IKrKKdAKBYBI/E7pl7PCJasHDLN5T1/ohF/qEuXyhwsm8d87xDvfmcxk590hp/2XuenQBDaGhI+IA==", "prop_sub_type"=>{"name"=>"sub foo", "prop_type_id"=>"1"}, "commit"=>"Create Prop sub type"}
(0.1ms) begin transaction
SQL (0.3ms) INSERT INTO "prop_sub_types" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2015-01-24 02:54:05.218673"], ["updated_at", "2015-01-24 02:54:05.218673"]]
(2.2ms) commit transaction
Redirected to http://localhost:3000/prop_sub_types/1
Completed 302 Found in 7ms (ActiveRecord: 2.6ms)
This is the relevant bit of schema.rb that demonstrates that the columns are there:
create_table "prop_sub_types", force: :cascade do |t|
t.string "name"
t.integer "prop_type_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Model:
class PropSubType < ActiveRecord::Base
attr_accessor :name, :prop_type_id
belongs_to :prop_type
has_many :appraisals
end
Controller (relevant portions for the sake of brevity -- I can post more if needed):
def create
#prop_sub_type = PropSubType.new(prop_sub_type_params)
respond_to do |format|
if #prop_sub_type.save
format.html { redirect_to #prop_sub_type, notice: 'Prop sub type was successfully created.' }
format.json { render :show, status: :created, location: #prop_sub_type }
else
format.html { render :new }
format.json { render json: #prop_sub_type.errors, status: :unprocessable_entity }
end
end
end
...
private
# Use callbacks to share common setup or constraints between actions.
def set_prop_sub_type
#prop_sub_type = PropSubType.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def prop_sub_type_params
params.require(:prop_sub_type).permit(:name, :prop_type_id)
end
app/views/prop_sub_types/_form.html.erb:
<%= form_for(#prop_sub_type) do |f| %>
<% if #prop_sub_type.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#prop_sub_type.errors.count, "error") %> prohibited this prop_sub_type from being saved:</h2>
<ul>
<% #prop_sub_type.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :prop_type_id %><br>
<%= f.number_field :prop_type_id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I'm adapting some Rails 3 code, so I thought I messed up the strong parameters portion, but the code actually looks correct to me and compares well with an unrelated, but working Rails 4 application.
What did I do wrong to make the INSERT ignore my parameters?
I believe it is because of your attr_accessor :name, :prop_type_id in model. Those accessors definitely are redundant and override the right ones: all fields for the DB table's fields are created as a part of initializing AR:Base class

Rails4 Nested Form not saving

I have a triple nested form where a Form has many questions and questions have many answers. I have each form rendering on the show page with the form title and the form questions and input fields to create new answers associated with the asked question. The association is linking up nicely, however I cant seem to get the answers to insert into the db. I feel like it is something real easy but I cant seem to figure it out.
-Form-
<%= simple_form_for #form do |f| %>
<%= f.error_notification %>
<h1><%= #form.name %></h1>
<div class="fields">
<%= f.simple_fields_for :form_questions do |q| %>
<%= label_tag q.index+1 %>
<%= q.simple_fields_for :form_answers, q.object.form_answers.build do |a| %>
<%= a.input :answer, label: false %>
<% end %>
<% end %>
</div>
<div class="fields">
<%= f.button :submit, :class => "button", value: 'Submit' %>
</div>
<% end %>
-Form Controller-
class FormsController < ApplicationController
def new
#form = Form.new
#form.form_questions.form_answers.build
end
def create
#form = Form.new(form_params)
end
def index
#forms = Form.includes(:form_questions).all
end
def show
#form = Form.find(params[:id])
end
def edit
#form = Form.find(params[:id])
end
def form_params
params.require(:form).permit(:id, :name, form_questions_attributes: [:title, form_answers_attributes: [:answer]])
end
end
-Form Answer Controller (although if the associations are correct I feel like I should be able to handle everything in the forms controller)
class FormAnswersController < ApplicationController
def new
#form_answer = FormAnswer.new
end
def create
#form_answer = FormAnswer.new(form_answer_params)
if #form_answer.save
RequestMailer.request_submit(#form).deliver
else
format.html {render action: 'new'}
end
end
def form_answers_params
params.require(:form_answer).permit(:form_id, :form_question_id, :id, :answer)
end
end
-Server Logs-
Started PATCH "/forms/12" for 127.0.0.1 at 2014-08-05 13:31:44 -0400
Processing by FormsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"CcaCGjdoYPH2Boi1prIFhG+h5YuPHQvAxMp1dcKvWr8=", "form"=>{"form_questions_attributes"=>{"0"=>{"form_answers_attributes"=>{"0"=>{"answer"=>"hey"}}, "id"=>"50"}, "1"=>{"form_answers_attributes"=>{"0"=>{"answer"=>"ya"}}, "id"=>"51"}, "2"=>{"form_answers_attributes"=>{"0"=>{"answer"=>"go"}}, "id"=>"52"}}}, "commit"=>"Submit", "id"=>"12"}
Rendered forms/update.html.erb within layouts/application (0.1ms)
Completed 200 OK in 12ms (Views: 11.4ms | ActiveRecord: 0.0ms)

Why am I getting argument out of range exception

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).

Resources