ActiveRecord 聚合和 form_for
我正在考虑对某些字段使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
批量分配有效(通过正常的属性编写器方法),但显然它不是通过聚合器类的初始化方法运行的。
通常也可以在 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.