2010-07-09 51 views
1

因此,我已閱讀&重新閱讀Stephen Chu關於該主題的文章(http://www.stephenchu.com/2008/05/rails-composedof-validation.html),但是我只是沒有任何運氣。composed_of&fields_for

按照例如在貨幣寶石文檔money.rubyforge .ORG提供

型號

class Payment < ActiveRecord::Base 
    composed_of :amount, 
    :class_name => "Money", 
    :mapping => [%w(cents cents), %w(currency currency_as_string)], 
    :constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) } 
end 

尼斯瘦控制器

class PaymentsController < ApplicationController 
    def create 
    @payment = Payment.new(params[:payment]) 
    ... 
    end 
end 

視圖(HAML)

- form_for @payment do |p| 
    - p.fields_for :amount, @payment.amount do |a| 
    = a.label :cents 
    = a.text_field :cents 
    = a.label :currency 
    = a.text_field :currency, :value => :usd 

我收到的錯誤是: 未定義的方法`美分爲{ 「美分」=> 「6.66」, 「貨幣」=> 「USD」}:HashWithIndifferentAccess

在 '量' 的散列被傳入compos_of爲'cents',但根據該文章,它應該從表單中使用params中的'amount'屬性。我只是非常卡住:/

回答

0

編輯:我誤解了你的問題。是的,在你的表格中你需要用這種方式參考amount

- form_for @payment do |p| 
    = a.label :dollars 
    = a.text_field :amount 
    = a.label :currency 
    = a.text_field :currency, :value => :usd