Alex Rivera | Logout

Accepts Nested Attribute with a virtual attribute

Asked 2011-04-09T00:44:53.403
10

I have a Project model which accepts nested attributes for tasks. And Task has a virtual attribute "name". So every time I change the name, it gets persisted as encrypted_task_name before update. On the project edit page the form has a input field for task name (and not encrypted_task_name). When I change the name and since name is a virtual attribute, Rails doesn't detect a change in Task and doesn't update that task while updating Project.

How do I make sure that task is saved even if its virtual attributes are changed during Project update?

One option that I don't want to use is :autosave => true on task.rb since I task is rarely updated.

Edit
Report

1 Answer

0

Check out Attribute Filters gem. It takes care of virtual attributes tracking (automagically wrapping setter methods) by adding attr_virtual DSL keyword and lets you do other things, like declarative filtering of attributes:

class User < ActiveRecord::Base
  include ActiveModel::AttributeFilters::Common::Split

  split_attribute   :real_name => [ :first_name, :last_name ]
  before_validation :filter_attributes

  attr_virtual  :real_name
  attr_accessor :real_name
end
answered 2012-11-04T16:05:48.510

Your Answer