开发者

accepts_nested_attributes_for virtual attributes

开发者 https://www.devze.com 2023-03-26 21:48 出处:网络
I have 2 models: class Invoice < ActiveRecord::Base has_many :invoice_items accepts_nested_attributes_for :invoice_items, :allow_destroy => true

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开发者_如何学Go_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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消