我有一个rails应用程序,其中"RFQ"具有日期时间属性。日期在表格中发生了更改,但我想将时间设置为15:00。
当我创建RFQ时,它工作正常,但如果我编辑它,它将变为00:00:00
创建操作:
def create
@rfq = Rfq.new(rfq_params)
@rfq.owner = current_user.email
@rfq.due = @rfq.due.change(hour: 15)
respond_to do |format|
if @rfq.save
format.html { redirect_to @rfq, notice: 'Rfq was successfully created.' }
format.json { render :show, status: :created, location: @rfq }
else
format.html { render :new }
format.json { render json: @rfq.errors, status: :unprocessable_entity }
end
end
end
更新动作
def update
@rfq.owner = current_user.email
@rfq.due = @rfq.due.change(hour: 15)
respond_to do |format|
if @rfq.update(rfq_params)
format.html { redirect_to @rfq, notice: 'Rfq was successfully updated.' }
format.json { render :show, status: :ok, location: @rfq }
else
format.html { render :edit }
format.json { render json: @rfq.errors, status: :unprocessable_entity }
end
end
end
创建后:
Rfq Load (0.2ms) SELECT "rfqs".* FROM "rfqs" ORDER BY "rfqs"."id" DESC LIMIT 1
=> Wed, 01 Jul 2015 15:00:00 CDT -05:00
在我编辑之后
Rfq Load (0.2ms) SELECT "rfqs".* FROM "rfqs" ORDER BY "rfqs"."id" DESC LIMIT 1
=> Tue, 30 Jun 2015 00:00:00 CDT -05:00
您的问题是,在使用表单中的值更新due
属性之前,您正在更改该属性。
你应该这样做:
def update
@rfq.owner = current_user.email
@rfq.attributes = rfq_params
@rfq.due = @rfq.due.change(hour: 15)
respond_to do |format|
if @rfq.save
format.html { redirect_to @rfq, notice: 'Rfq was successfully updated.' }
format.json { render :show, status: :ok, location: @rfq }
else
format.html { render :edit }
format.json { render json: @rfq.errors, status: :unprocessable_entity }
end
end
end