Rahul Bhargava
Rahul Bhargava

Reputation: 548

How to save date select fields in rails

How do I save date select field?

Say, I have this in my views:

 <%= f.date_select :dob, :start_year => Date.current.year, :end_year => 1920 %>

This would be converted to HTML as :

<select id="user_dob_1i" name="user[dob(1i)]"> ..for year..

<select id="user_dob_2i" name="user[dob(2i)]"> ..for month..

<select id="user_dob_3i" name="user[dob(3i)]"> ..for date..

Above select value will of-course have some options.

Now, when I submit the page/form, parameters will be passed as:

 Parameters: {"utf8"=>"✓", "user"=>{"dob(1i)"=>"2015", "dob(2i)"=>"3", "dob(3i)"=>"24"}, "commit"=>"Register"}

Make sense?

In my database, I have field called 'dob'. Question is how do I save this field in my database?

I am using Rails 4.0.2 and using the params permit feature. I have added this in my controller,

params.require(:user).permit("dob(1i)", "dob(2i)", "dob(3i)")

Googled about it but I did not reach fair conclusion on it..

Upvotes: 1

Views: 1688

Answers (1)

Beartech
Beartech

Reputation: 6411

Just create a date from the three params:

@user.dob = Date.new(params['dob(1i)'].to_i,params['dob(2i)'].to_i,params['dob(3i)'].to_i)

@user.save

Just FYI, Rails will accept an actual string as a date for a column in the DB of type DATE. So if you use a date picker that returns a string like:

# if params[dob] = '2015-3-26' passed from your form
@user.dob = params[dob]
@user.save
  # in server console you'll see...
  # SQL (0.6ms)  UPDATE "users" SET "dob" = $1, "updated_at" = $2 WHERE "users"."id" = 193  [["dob", Thu, 26 Mar 2015],...

So you could do something like:

@user.dob = params.values.join'-'
  # =>'2015-3-26'
@user.save

Of course if you add any other params to your form and your permit, then that one would no longer work. I advise you look at date-pickers for your forms. Makes everything easy.

Upvotes: 3

Related Questions