Accepts_nested_attributes_for 虚拟属性
我有 2 个模型:
class Invoice < ActiveRecord::Base
has_many :invoice_items
accepts_nested_attributes_for :invoice_items, :allow_destroy => true
end
class InvoiceItem < ActiveRecord::Base
attr_accessor :encryption_key
belongs_to :invoice
end
发票项目的列已加密,并且我使用来自会话的加密密钥。我不希望将此密钥存储在服务器或任何其他模型中。
从控制器:
params[:invoice][:invoice_items_attributes].each_value {
|v| v.merge!(:encryption_key => session['access_key'])
}
@invoice = Invoice.new(params[:invoice])
这会将密钥很好地放入属性列表中,但在创建发票时不会将其传递给 InvoiceItems 模型...
任何有关如何使其工作的指示都会很棒。
I have 2 models:
class Invoice < ActiveRecord::Base
has_many :invoice_items
accepts_nested_attributes_for :invoice_items, :allow_destroy => true
end
class InvoiceItem < ActiveRecord::Base
attr_accessor :encryption_key
belongs_to :invoice
end
The columns for invoice items are encrypted and I use an encryption key that comes from a session. I don't want this key stored on the server or in any other model.
From the controller:
params[:invoice][:invoice_items_attributes].each_value {
|v| v.merge!(:encryption_key => session['access_key'])
}
@invoice = Invoice.new(params[:invoice])
This puts the key into the attributes list fine but it is then not passed to the InvoiceItems model when creating an invoice...
Any pointers on how to get this working would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是,由于字段是虚拟属性,您需要遍历发票项目模型字段的 setter 方法,因此您将必须手动编写解决方案代码,而不是依赖嵌套属性。
实现此目的的一种方法是创建一个特定的方法来处理发票模型类上的发票项目。您可以将参数传递到该方法中,并在该方法中处理创建/查找发票项目,将参数分配给正确的 setter 方法,这些方法处理发票项目类上的加密,然后直接从控制器调用该方法。
The thing is that as the fields are virtual attributes you need to go through the setter methods of the fields for your invoice items model so you are going to have to hand code your solution rather than rely on nested attributes.
One way of achieving this would be to create a specific method to handle invoice items on the invoice model class. You could pass the params into that method and deal with creating/finding an invoice item in that method assigning the params to the correct setter methods that handle the encryption on the invoice_item class then call that method directly from your controller.