简体   繁体   中英

How to get the value of date_select field in Rails?

I need to get the value of the date_select field in my controller. I also need to add an if statement so that if the value is nil it won't try to get the data and trow an error.

Here's my date_select field :

<%= date_select :regdate, :date, order: [:year, :month] %>

Here's the params in the debug :

regdate: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  date(3i): '1'
  date(1i): '2014'
  date(2i): '10' 

In the controller side

regdate =  Date.new(params["regdate(1i)"].to_i,
                    params["regdate(2i)"].to_i,
                    params["regdate(3i)"].to_i)

or this, whatever coming in your params

regdate =  Date.new(params["date(1i)"].to_i,
                    params["date(2i)"].to_i,
                    params["date(3i)"].to_i)

I think this notation looks nicer in code:

foo = Date.new(*params[:foo].map { |_, v| v.to_i })

That requires you to set the prefix option in date_select , which moves all inputs for year, month and day into an hash:

<%= f.date_select 'start_date', prefix: 'foo'} %>

In the controller use

@regdate = params

And inner the view

<%= @regdate["regdate"]["date(3i)"]  %>
<%= @regdate["regdate"]["date(2i)"]  %>
<%= @regdate["regdate"]["date(1i)"]  %>

I found date_select to be a bit tricky because of the format of the params it will generate, but to use the question at hand, here's a full explaination. Starting with the view:

# View
= date_select :regdate, :date, order: [:year, :month]

Above code will give a Year and a Month selector. So in the params that will be passed to the backend/rails app:

# Console
Parameters: {"utf8"=>"✓", "regdate"=>{"date(3i)"=>"1", "date(1i)"=>"2014", "date(2i)"=>"3"}, "commit"=>"Send"}

You are only looking for the first two values: Year, month

In backend/controller use following code to convert the params back into a date of any kind:

# Controller
selected_date =  Date.new(
  params[:download_date]["download_date(1i)"].to_i,
  params[:download_date]["download_date(2i)"].to_i
  ).strftime("%Y%m%d")

Note that attaching .strftime("%Y%m%d") at the end of the Date object will let to format the resulting date in any way you like. In this case it will result in:

201403

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM