Ruby on rails RubyonRails中的虚拟属性
我是Rails的新手。我不明白我做错了什么 我有以下model order.rb,带有虚拟属性值:Ruby on rails RubyonRails中的虚拟属性,ruby-on-rails,ruby,rails-activerecord,Ruby On Rails,Ruby,Rails Activerecord,我是Rails的新手。我不明白我做错了什么 我有以下model order.rb,带有虚拟属性值: class Order < ActiveRecord::Base ACTIONS = %w(buy sell) ORDER_TYPES = %w(LMT STP) TIFS = %w(DAY GTC OPG IOC) attr_accessible :action, :price, :quantity, :symbol, :tif,
class Order < ActiveRecord::Base
ACTIONS = %w(buy sell)
ORDER_TYPES = %w(LMT STP)
TIFS = %w(DAY GTC OPG IOC)
attr_accessible :action, :price, :quantity, :symbol, :tif, :order_type, :value
validates :action, :symbol, :tif, :order_type, presence: true
validates :price, numericality: { greater_than_or_equal_to: 0.0001 }
validates :quantity, numericality: { only_integer: true, greater_than: 0 }
validates :action, inclusion: ACTIONS
validates :order_type, inclusion: ORDER_TYPES
validates :tif, inclusion: TIFS
def value
price * quantity
end
def value= (val)
self.quantity = val / self.price
end
end
类顺序
这个模型在rails控制台中运行良好,我可以在这里设置值并计算数量
问题是当我试图将表单可视化时。
app/views/orders/new.html.erb呈现以下内容:
<%= form_for @order, html: { :class => 'form-inline' } do |f| %>
<% if @order.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@order.errors.count, "error") %> prohibited this order from being saved:</h2>
<ul>
<% @order.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<fieldset>
<legend><%= params[:action].capitalize %> Order</legend>
<table class="table">
<thead>
<tr>
<th><%= f.label :action %></th>
<th><%= f.label :symbol %></th>
<th><%= f.label :price %></th>
<th><%= f.label :value %></th>
<th><%= f.label :order_type %></th>
<th><%= f.label :tif, "TIF" %></th>
</tr>
</thead>
<tbody>
<tr>
<td><%= f.select :action, Order::ACTIONS, {}, class: 'input-small' %></td>
<td><%= f.text_field :symbol, class: 'input-small' %></td>
<td><%= f.text_field :price, class: 'input-small' %></td>
<td><%= f.text_field :value, class: 'input-small' %></td>
<td><%= f.select :order_type, Order::ORDER_TYPES, {}, class: 'input-small' %></td>
<td><%= f.select :tif, Order::TIFS, {}, class: 'input-small' %></td>
</tr>
</tbody>
</table>
<%= f.submit "Submit", class: "btn btn-primary" %>
<%= f.submit "Clear", class: "btn", type: "reset" %>
</fieldset>
<% end %>
'forminline'}do | f |%>
禁止保存此订单:
命令
在浏览器中打开页面时出错,该页面在_form.html.erb行中出现,文本字段值为:
订单中的命名错误#新
nil:NilClass的未定义方法“*”
我做错了什么?我试图遵循,因为新建的订单对象价格为零。所以你得到了这个错误 在计算价值之前,请确保您有价格和数量
def value
return unless price || quantity
price * quantity
end
对于新建订单,目标价格为零。所以你得到了这个错误 在计算价值之前,请确保您有价格和数量
def value
return unless price || quantity
price * quantity
end
“订单”表中有“值”列吗?在“订单”表中有“值”列吗?谢谢,现在我明白了!我还修改了二传手,你同意吗?def值返回,除非价格和数量价格*数量结束def值=(val)返回,除非self.price self.quantity=val/self.price end谢谢,现在我明白了!我还修改了二传手,你同意吗?def值返回,除非价格和数量价格*数量结束def值=(val)返回,除非self.price self.quantity=val/self.price结束