简体   繁体   中英

rails check complete date_select and time_select param

I have an update form where I want a user to update a date. The date should always be NEWER than the date which is currently in the database so I want my script to validate it after the user hits the submit button. I've come this far:

<%= simple_form_for(calendar, :html => { :method => :put, :name => 'extend_link' }) do |f| %>

<p>Select the new date (must be newer than the current date): <%= f.date_select :end_at %> at <%= f.time_select :end_at, { :ignore_date => true } %></p>

<% end %>

standard update put in my controller, updating the calendar model

  def update
    @calendar = current_user.calendar.find(params[:id])

      respond_to do |format|
        if @calendar.update_attributes(params[:calendar])
          format.html { redirect_to calendar_path, notice: 'The end date was extended.' }
          format.json { head :no_content }
        end
      end

  end

I've checked the source after the form was rendered to understand how the date and time select works and also after researching a lot it is clear that the date is being split into different pieces before it is "merged" into my model and the end_at column

calendar[end_at(3i)]
calendar[end_at(2i)]
....

but for some reason, I cannot access the complete params[:end_at] after the form was submitted. However, it mus be accessible as otherwise how could the model get updated in one piece? I went nuts with this.

It could be so easy:

if params[:end_at] < @calendar.end_at
 puts "The new ending date is not after the current ending date."
else
 @calendar.update_attributes(params[:calendar])
end

why does it not work and how I can solve my problem?

Thanks for any help.

You can do this in your controller, but it sounds like this is a model validation, so I'd put it there. Use the magic of ActiveModel::Dirty to find the attribute before and after, perhaps something like this:

class Calendar < ActiveRecord::base

  validate :date_moved_to_future

  private

  def date_moved_to_future
     self.errors.add(:end_at, "must be after the current end at") if self.end_at_changed? && self.end_at_was < self.end_at
  end
end

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