Rails Money Gem“未初始化的恒定货币::货币::表”在视图中

时间:2012-05-30 07:58:29

标签: ruby-on-rails gem currency

我有钱币宝石的问题。我试图显示所有货币的下拉列表:

观点:

<% if @receipt.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(@receipt.errors.count, "error") %> prohibited this receipt from being saved:</h2>
  <ul>
    <% @receipt.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
    <% end %>
  </ul>
</div>
<% end %>
<%= simple_form_for(@receipt, :html => {:class => 'form-horizontal', :multipart => true }) do |f| %>
<h3>Kassenzettel hinzufügen</h3>
  <p>
  <div class="input-prepend">
    <%= f.label :due_date, 'Ausstellungsdatum' -%>
    <span class="add-on"><i class="icon-calendar"></i></span><%= f.text_field :due_date,  :value => Date.today.strftime('%d.%m.%Y'), :class => 'datepicker span2', :"data-date-format" => :'dd.mm.yyyy' %>
    </p>
    <p>
    <%= f.label :due_time, 'Zeit (optional)' -%>

    <%= f.time_select :due_time, { :class => "adsf"} %>
    </p>
    <p>
      <%= f.select(:currency,all_currencies(Money::Currency::TABLE), {:include_blank => 'Select a Currency'}) %>

    </p>
    <p> <%= f.label :recipt, 'Datei hochladen' -%> <%= f.file_field :document -%>
    <p class="help-block">Akzeptierte Formate: PDF, JPG, TIFF, max. 1 MB</p>
    </p>
    <br />
    <p>
      <button type="submit" class="btn btn-success"><i class="icon-plus icon-white"></i> Dokument hinzufügen </button>
      <%= link_to 'Abbrechen', receipts_path, :class => "btn" %></p>  
<% end %>

模特:

class Receipt < ActiveRecord::Base  

    belongs_to :user
    has_many   :products, :dependent => :destroy
    self.per_page = 5   
    validates :due_date, :presence => true
    validates_attachment :document, :presence => true,            
              :size => { :in => 0..5024.kilobytes }
    has_attached_file :document,
    :styles => {
        :minithumb=> ["50x50#", :png],
        :thumb=> ["150x150#", :png],
        :small  => ["500>", :png]       },
    :convert_options => { :all => '-background white -flatten +matte'}
    attr_accessible :due_date, :due_time, :receiptissuedate, :document, :dependent => :destroy
    columns_hash["due_time"] = ActiveRecord::ConnectionAdapters::Column.new("due_time", nil, "time")

    composed_of :receiptfinalamount,
        :class_name => "Money",
        :mapping => [%w(receiptfinalamount cents), %w(receiptcurrency currency_as_string)],
        :constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) },
        :converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") }

    before_validation(:on => :create) do
        self.receiptissuedate = DateTime.new(self.due_date.year, self.due_date.month, self.due_date.day, self.due_time.hour, self.due_time.min)
    end

    before_save :default_values
    def default_values
        self.receiptfinalamount ||= 0
    end

    def due_date
        return @due_date if @due_date.present?
        return Date.today
    end

    def due_time
        return @due_time if @due_time.present?
        return Time.now
    end 


    def due_date=(new_date)
        @due_date = self.string_to_datetime(new_date, I18n.t('date.formats.default'))
    end


    def due_time=(new_time)
        @due_time = self.string_to_datetime(new_time, I18n.t('time.formats.time'))
    end

    protected

    def string_to_datetime(value, format)
        return value unless value.is_a?(String)

        begin
            DateTime.strptime(value, format)
        rescue ArgumentError
            nil
        end
    end

end

控制器:

class ReceiptsController < ApplicationController


  helper_method :sort_column, :sort_direction

  # GET /receipts
  # GET /receipts.json
  def index
    #@receipts = Receipt.all
    @receipts = current_user.receipts.order(sort_column + " " + sort_direction).paginate(:page => params[:page]).order('receiptissuedate DESC') 

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @receipts }     
    end
  end


  # GET /receipts/1
  # GET /receipts/1.json
  def show
    @receipt = current_user.receipts.find(params[:id])
    @products = current_user.receipts.find(params[:id]).products.all
    @product = Product.new

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @receipt }
    end
  end

  # GET /receipts/new
  # GET /receipts/new.json
  def new

    @receipt = Receipt.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @receipt }
    end
  end

  # GET /receipts/1/edit
  def edit
    @receipt = Receipt.find(params[:id])
  end

  # POST /receipts
  # POST /receipts.json
  def create
    @receipt = current_user.receipts.new(params[:receipt])

    respond_to do |format|
      if @receipt.save
        format.html { redirect_to receipts_url, notice: 'Receipt was successfully created.' }
        format.json { render json: @receipt, status: :created, location: @receipt }
      else
        format.html { render action: "new" }
        format.json { render json: @receipt.errors, status: :unprocessable_entity }
      end
    end
  end
  # PUT /receipts/1
  # PUT /receipts/1.json
  def update
    @receipt = current_user.receipts.find(params[:id])

    respond_to do |format|
      if @receipt.update_attributes(params[:receipt])
        format.html { redirect_to @receipt, notice: 'Receipt was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @receipt.errors, status: :unprocessable_entity }
      end
    end
  end


  # DELETE /receipts/1
  # DELETE /receipts/1.json
  def destroy
    @receipt = current_user.receipts.find(params[:id])
    @receipt.destroy

    respond_to do |format|
      format.html { redirect_to receipts_url }
      format.json { head :no_content }
    end
  end

  private

  def sort_column
    Receipt.column_names.include?(params[:sort]) ? params[:sort] : "receiptissuedate"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "desc"
  end
end

错误:

收据中的NameError#new

显示/Users/dastrika/Documents/RailsProjects/receipter/app/views/receipts/_form_new.html.erb第22行:

未初始化的常数Money :: Currency :: TABLE

提取的来源(第22行):

19:&lt;%= f.label:due_time,&#39; Zeit(可选)&#39; - %GT; 20:
21:&lt;%= f.time_select:due_time,{:class =&gt; &#34; adsf&#34;}%&gt; 22:

23:

24:&lt;%= f.select(:currency,all_currencies(Money :: Currency :: TABLE),{:include_blank =&gt;&#39;选择货币&#39;})%&gt; 25:

模板包含跟踪:app / views / receipts / new.html.erb

Rails.root:/ Users / dastrika / Documents / RailsProjects / receipter 应用程序跟踪|框架跟踪|完整跟踪

app / views / receipts / _form_new.html.erb:22:in block in _app_views_receipts__form_new_html_erb__159753442_6920660' app/views/receipts/_form_new.html.erb:11:in _ app_views_receipts__form_new_html_erb__159753442_6920660&#39; app / views / receipts / new.html.erb:7:in _app_views_receipts_new_html_erb__164008852_34408570' app/controllers/receipts_controller.rb:38:in new&#39;

2 个答案:

答案 0 :(得分:2)

此语法不正确

Money::Currency::TABLE

你想要

all_currencies(Money::Currency.table)

def all_currencies(hash)
  hash.keys
end

http://rubymoney.github.com/money/

答案 1 :(得分:0)

运行example from the rubymoney docs时出现类似的错误消息

Money.new(1000, "USD") == Money.new(1000, Currency.new("USD"))
NameError: uninitialized constant Currency

要解决此问题,我只需在Money::的调用之前加上Currency,就像这样:

Money.new(1000, "EUR").currency == Money::Currency.new("EUR")
=> true