由 & 组成字段_for

发布于 2024-09-08 14:05:57 字数 1282 浏览 2 评论 0原文

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

中提供的示例,

根据 Money gem 文档 Money.rubyforge .org Model

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

Nice Skinny Controller

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

View (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

我收到的错误是: undefined method `cents' for {"cents"=>"6.66", "currency"=>"usd"}:HashWithIn DifferentAccess

'amount' 哈希值被作为 'cents' 传递到composed_of 中,但根据文章,它应该使用表单中参数中的“金额”属性。我真的被困住了:/

So I have read & re-read the Stephen Chu article on the topic (http://www.stephenchu.com/2008/05/rails-composedof-validation.html), however I am just not having any luck.

Per the example on provided in the money gem documentation money.rubyforge .org

Model

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

Nice skinny controller

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

View (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

The error I receive is:
undefined method `cents' for {"cents"=>"6.66", "currency"=>"usd"}:HashWithIndifferentAccess

The 'amount' hash is being passed into composed_of as 'cents', but according to the article, it should use the attributes of 'amount' in params from the form. I'm just really stuck :/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

递刀给你 2024-09-15 14:05:57

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

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

Edit: I misunderstood your question before. Yes, in your forms you need to reference amount this way:

- form_for @payment do |p|
   = a.label :dollars
   = a.text_field :amount
   = a.label :currency
   = a.text_field :currency, :value => :usd
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文