date_select不保留从新编辑视图到编辑视图的日期参数

时间:2014-05-26 05:55:51

标签: ruby-on-rails forms date datetime

用户在新表单页面上启动,在提交后,他们会立即重定向到编辑页面,在那里他们会看到他们刚刚提交的信息,并有机会进行更改。之前发布的数据应该会延续,现在除了日期(:startdate:enddate)之外他们也会继续...

即,如果您在新页面上输入email:john@gmail.com,然后在编辑页面上输入,则john @gmail.com已经可见,以防您需要进行更改。但是,日期字段会保持重置为当前日期。

感谢您的帮助!

CONTROLLER代码

class RequestsController < ApplicationController

  def new
    @requestrecord = Request.new
  end

  def create
    @requestrecord = Request.new(request_params)
    if @requestrecord.save
      redirect_to edit_request_path(@requestrecord.edit_id)
    else
      render 'new'
    end
  end

  def edit 
    @requestrecord = Request.find_by_edit_id(params[:edit_id])
  end

  def update
    @requestrecord = Request.find_by_edit_id(params[:edit_id])
    @requestrecord.attributes = request_params
  end

private
  def request_params
    params.require(:request).permit(:email, :startdate, :enddate, :edit_id) #edit_id is auto-gen by a method defined in the model
  end

查看代码

<%= form_for @requestrecord, :html=> {:id => 'form'} do |f| %>

    <div class="form-group">
       <%= f.label :email, "Email we will use to contact you" %>
       <%= f.text_field :email, class: "form-control", placeholder: "How do we get in touch with you?" %>
    </div>

    <div class="form-group">
       <%= f.label "Item(s) needed from: " %>
       <%= date_select(:request, :startdate, start_year: Date.today.year, end_year: Date.today.year + 1) %>
       <%= f.label " to: " %>
       <%= date_select(:request,   :enddate, start_year: Date.today.year, end_year: Date.today.year + 1) %>
    </div>

    <%= f.submit "Go!", class: "btn btn-primary btn-large btn-block" %>

<% end %>

模型代码

  private

    def Request.new_edit_id
      SecureRandom.urlsafe_base64
    end

    def create_edit_id
      self.edit_id = Request.new_edit_id
    end

我尝试过的事情(没有奏效)

  • :startdate:enddate列类型从:datetime更改为:date
  • 由于编辑页面和新页面都是使用表单从相同的部分绘制的,我认为原生默认日期可能会不断超越params,所以我尝试包含选项include_blank: true,这没有&# 39;工作,现在日期只是重置为编辑页面上的空白
  • 尽管日期重置,但要清楚它们总是保存在数据库中,所以params通过了。但为了清楚起见,我已经尝试了许多不同的参数选项,从"startdate(1i)", "startdate(2i)", "startdate(3i)":startdate => [],将startdate完全分开作为单独的参数请求,按照此example < / LI>

1 个答案:

答案 0 :(得分:0)

GAH!显然不同于简单形式的其他每个参数,date_select不断默认返回默认值(即今天或空白,无论你告诉它什么)即使你没有指定默认值!

我正在使用一个表单作为新的&amp;部分。编辑页面。渲染编辑页面时,Rails足够智能,可以用:email之前的:params替换:email的占位符,但是对于日期,您必须明确告诉它默认值应该是该实例变量的已存储日期。

<div class="form-group">
   <%= f.label :email, "Email we will use to contact you" %>
   <%= f.text_field :email, class: "form-control", placeholder: "How do we get in touch with you?" %>
</div>

<div class="form-group">
   <%= date_select(:request, :startdate, default: @requestrecord.startdate, start_year: Date.today.year, end_year: Date.today.year + 1) %>
</div>