Accepts_nested_attributes_for 虚拟属性

发布于 2024-11-28 13:56:45 字数 662 浏览 0 评论 0原文

我有 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 技术交流群。

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

发布评论

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

评论(1

¢蛋碎的人ぎ生 2024-12-05 13:56:45

问题是,由于字段是虚拟属性,您需要遍历发票项目模型字段的 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.

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