如何从“ date_select”获取日期并进行验证?

时间:2019-04-17 07:19:57

标签: ruby-on-rails ruby

我是红宝石的初学者。 我想从表单中获取日期并在子类中对其进行验证,但是我不知道如何实现它们。也许我不知道如何从哈希中获取日期。请帮助我。

# HTML
<%= form_with model: @order, scope: :order, url: update_signed_in_show_employer_url(order.employer, order_id: order.id) , method: :put, class: '' do |f| %>
  <div class="form-group">
    <label>start date:</label>
    <% if order.signed_at.present? %>
    <%= f.date_select :started_at, {default: order.signed_at}, { class: 'form-control m-b' } %>
    <% end %>
  </div>
<% end %>
# controller
def update_signed_in_show
  @employer = Employer.find(params[:id])
  logger.debug "singned_params: #{signed_params}"
  @order = Order::Signed.find(params[:order_id])

  ......
end
# class Order::Signed < Order
validate :check_started_at
def check_started_at
  if self.started_at.present? && self.ended_at.present?
    if self.started_at.to_datetime < self.signed_at.to_datetime
      errors.add :started_at, 'xoxoxoxoxo.......'
    end
  end
end

在控制器中,我可以读取表格中的参数。 杂凑: {“ started_at(1i)” =>“ 2019”,“ started_at(2i)” =>“ 4”,“ started_at(3i)” =>“ 17”,“ ended_at(1i)” =>“ 2022”,“ end_at(2i)“ =>” 4“,” ended_at(3i)“ =>” 17“,” remark_of_signed“ =>”“,” status“ =>” signed“}

我想在子类中进行验证,但是收到一个错误:

NoMethodError(未定义的方法to_datetime' for nil:NilClass): app/models/order/signed.rb:20:in check_started_at'

1 个答案:

答案 0 :(得分:0)

感谢Siim Liiser的帮助,我已经能够成功进行验证。

# Order::Entered < Order
validate :check_ended_at

def check_ended_at
  if self.started_at.present? && self.ended_at.present?
    if self.ended_at < (self.started_at + signed_years_count.year)
      errors.add :started_at, 'error message...'
    end
  end
end