Set the start time and end time on the bulletin board and create a site to recruit people. Set validation so that the end time does not come before the start time. (* In addition, add validation that the start time does not come before the current date and time)
Ruby 2.5.0 Rails 6.0.3.4
When creating a recruitment board, set it so that you can enter the start time and end time.
This time, the recruitment version is called board. The contents of the table are as ↓
XXXX_create_boards.rb
class CreateBoards < ActiveRecord::Migration[6.0]
def change
create_table :boards do |t|
(Omitted)
t.datetime :start_time, null: false
t.datetime :finish_time, null: false
t.timestamps
end
end
end
Set the start time in the "start_time" column and the end time in the "finish_time" column.
I have set the following validations.
models/board.rb
validates :start_time, presence: true
validates :finish_time, presence: true
validate :start_finish_check
validate :start_check
def start_finish_check
errors.add(:finish_time, "Please select a time later than the start time") if self.start_time > self.finish_time
end
def start_check
errors.add(:start_time, "Please select a time later than the current date and time") if self.start_time < Time.now
end
I will briefly explain each of them.
models/board.rb
validate :start_finish_check
validate :start_check
Here, we are verifying each process. Notice that it is validate
instead of validates
. If it is validate
, you will get the error" You need to supply at least one validation ".
def start_finish_check
errors.add(:finish_time, "Please select a time later than the start time") if self.start_time > self.finish_time
#Comparison of start time and end time with ↑
end
def start_check
errors.add(:start_time, "Please select a time later than the current date and time") if self.start_time < Time.now
#↑ to compare the start time and the current date and time
end
Here we are comparing each time. If ʻifis true, an error statement will be added. It is not necessary to write it, but it is also possible to write the direction of the inequality sign
> or rewrite ʻif
as ʻunless. Also, the same process is performed without writing
self`.
That area is your choice.
This time it was a comparison of Datetime type, but I think that it can be implemented in the same way for other types. ↓ is a reference article for getting the date and time Get the current date and time with ruby [Differences between Time, Date, DateTime, TimeWithZone between Ruby and Rails] (https://qiita.com/jnchito/items/cae89ee43c30f5d6fa2c)
How to validate datetime type input before and after with rails [Validation] rails How to specify after today's date