ActiveRecord 聚合和 form_for

发布于 2024-10-15 10:15:46 字数 795 浏览 6 评论 0原文

我正在考虑对某些字段使用 ActiveRecord 聚合器。

让我困扰的是聚合属性与 form_for 和输入字段的配合效果如何。也就是说,如何生成聚合属性的输入字段(因为它们是只读的)?

就像,让我们以 http://api.rubyonrails.org/classes/ 为例ActiveRecord/Aggregations/ClassMethods.html

class Customer < ActiveRecord::Base
    composed_of :balance, :class_name => "Money", :mapping => %w(balance amount)
    composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
  end

class Money
   attr_reader :amount, :currency

   def initialize(amount, currency = "USD")
     @amount, @currency = amount, currency
   end
 end

现在,假设我们有一个表格,允许客户输入自己的余额。如何制作 form_for 并生成余额的输入字段?另外,平衡验证属于哪里?批量分配有效吗?

I'm contemplating about using an ActiveRecord aggregator for some fields.

The thing that bothers me that how well do aggregated attributes work with form_for and input fields. That is, how do you generate the input fields for the aggregated attributes (since they are read only)?

Like, lets take the example from http://api.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html .

class Customer < ActiveRecord::Base
    composed_of :balance, :class_name => "Money", :mapping => %w(balance amount)
    composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
  end

class Money
   attr_reader :amount, :currency

   def initialize(amount, currency = "USD")
     @amount, @currency = amount, currency
   end
 end

Now, lets say we had a form, where customer would be allowed to input his own balance. How do you make that form_for and generate the input fields for balance? Also, where do validations for balance belong to? Does mass assigment work?

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

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

发布评论

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

评论(1

恏ㄋ傷疤忘ㄋ疼 2024-10-22 10:15:46

批量分配有效(通过正常的属性编写器方法),但显然它不是通过聚合器类的初始化方法运行的。

通常也可以在 Customer 类上设置验证。

Mass assignment works (through the normal attribute writer methods), but apparently it isn't ran through the aggregator class's initialize method.

Validations also can be normally set on the Customer class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文