在我的Rails 3.2应用程序中,我想根据用户输入的字段值是变量的计算填充一些字段。但是,使用我当前的代码,计算似乎只能基于数据库中已有的值进行工作 - 它在初始保存时不能正确计算,但如果我返回记录并保存一秒钟,计算就会正确计算时间。 基于计算填充Rails字段
用户以入门级价格创建一个贸易
- entry_price
- exit_price:
我在我的模型(贸易)有这四个领域,然后稍后用exit_price编辑交易。当输入exit_price时,应用程序应计算percent_result和dollar_result。但是,现在,这些结果字段在第一次更新时没有正确填充 - 这似乎是因为它不会从字段中读取exit_price(当用户在表单中输入时),只有在它保存在D B。
我的控制器出了什么问题?
我的控制器:
def update @trade = Trade.find(params[:id]) exit_price = params[:trade][:exit_price] if !exit_price.blank? @trade.percent_result = ((exit_price.to_f - @trade.entry_price)/@trade.entry_price) * 100 @trade.dollar_result = exit_price.to_f - @trade.entry_price end params[:trade][:exit_date] = Date.strptime(params[:trade][:exit_date], '%m/%d/%Y') unless params[:trade][:exit_date].blank? params[:trade][:entry_date] = Date.strptime(params[:trade][:entry_date], '%m/%d/%Y') unless params[:trade][:entry_date].blank? respond_to do |format| if @trade.update_attributes(params[:trade]) format.html { redirect_to @trade, :flash => {:share =>"Your trade was successfully updated. Don't forget to share it with your friends, so you can profit together!"} } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @trade.errors, status: :unprocessable_entity } end end end
认为
<%= simple_form_for(@trade, :html=>{:class=> "form-horizontal well"}) do |f| %> <%= f.text_field :entry_price, :class=>"input-small" %> <%= f.text_field :exit_price, :class=>"input-small" %> <%= submit_tag "Edit Trade" %> <% end %>