A
A
Anton Misyagin2016-03-03 21:36:42
Ruby on Rails
Anton Misyagin, 2016-03-03 21:36:42

How to write the date to the database?

rails 4, sqlite
A field in a DATE type database. Gets from the database in the format yyyy-mm-dd. When rendering, I convert to dd.mm.yyyy. I edit in the browser in the same format. I send everything to the server in the same format dd.mm.yyyy. Attention to the question: How to convert to yyyy-mm-dd just before writing to the database, because rails wants to get the date in this format? If the question is clear, then you can not read further, otherwise you can get confused). In controller:

def update
  @model.update_attributes(x)
end

Moreover, everything is complicated with x , it all depends on various parameters. There are many of them, they may or may not be, they may be called one way or another. In view of this, I do not want to explicitly indicate which of the arrived parameters of the date type and convert them in the controller. It seems to me that it is somehow necessary in the model / lyas (because they are related) to declare this transformation, but I still don’t know how the rails handle this. For example, there is a warranty field (warranty up to). Then in the model if you declare:
def warranty
  '08.03.2016'
end

Then the eighth of March will always get out of the base. But this is for reading, but what about for writing?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Misyagin, 2016-03-03
@sunnmas

In total, in the model code, you need to declare a getter and a setter:

attr_accessor :warranty
  def warranty=(value)
    write_attribute :warranty, value.to_date
  rescue
            #если строка, пришедшая в параметрах не валидна, в базу пойдет null
  end
  def warranty
    self[:warranty].strftime '%d.%m.%Y' if self[:warranty]
  end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question