Save only the year in a date field on Postgres! RAILS

Asked

Viewed 264 times

0

I have two fields called start_year and end_year, in which I want to save only the year that the user will select and save in the database. But when you save the form that is processed by RAILS, it saves year, month and day. inserir a descrição da imagem aqui

I wonder if I can save a date type data in Postgres by storing only the year through RAILS.

On the web page and basically as soon as you get the data inserir a descrição da imagem aqui

That in html.erb the code is like this [inserir a descrição da imagem aqui]

In the database there is a table that would be the one that is the creation of user by.

inserir a descrição da imagem aqui

And in this photo below are the fields that are added to the user table, in which follows the fields start_year and end_year

inserir a descrição da imagem aqui

1 answer

1

In this case, you will have to change the field type in the database in your Migration.

of - (instead of using datetime)

create_table :nome_da_tabela do |t|
  t.datetime :inicio_ano
  t.datetime :termino_ano
end

To - (use an integer)

create_table :nome_da_tabela do |t|
  t.integer :inicio_ano
  t.integer :termino_ano
end

And in time to save you must extract the year. Example: Time.year returns 2018

  • In case I can not extract only year of type DATE?

  • can yes. Time was just an example, the syntax is the same

  • Where exactly do I get the year? Since I’m working on Users

  • Edit your post and paste some code, so we know how you’re doing.

  • You can extract the year but it is not the correct one. You will spend storage saving the date there, the best solution is to change the field to whole.

  • I understand Alex Takitani, but I don’t know how to make a select that shows the years and saves a whole

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.