0

私はRailsの初心者です。私はここで何が間違っているのか理解していません。

次のモデル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, :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.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 %>

ブラウザでページを開くと、_form.html.erbの行にテキストフィールドの値が表示されてエラーが発生します。

Orders#new undefined method `*'for nil:NilClassのNoMethodError

私は何が間違っているのですか?http://railscasts.com/episodes/16-virtual-attributesをフォローしようとしました

4

1 に答える 1

3

新しく構築された注文オブジェクトの価格はゼロです。したがって、このエラーが発生します。

値を計算する前に、価格と数量があることを確認してください

  def value
    return unless price || quantity
    price * quantity
  end
于 2013-01-24T13:11:32.167 に答える