composition_of& fields_for

时间:2010-07-09 01:00:31

标签: ruby-on-rails fields-for

所以我读过&重新阅读Stephen Chu关于这个主题的文章(http://www.stephenchu.com/2008/05/rails-composedof-validation.html),但是我没有运气。

根据money gem文档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

我收到的错误是: 未定义的方法`美分'为{“美分”=&gt;“6.66”,“货币”=&gt;“usd”}:HashWithIndifferentAccess

'amount'散列被传递给composed_of为'cents',但根据文章,它应该使用表格中params中'amount'的属性。我真的卡住了:/

1 个答案:

答案 0 :(得分:0)

编辑:我以前误解了你的问题。是的,在您的表单中,您需要以这种方式引用amount

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