Module: AttributeFu::Associations::ClassMethods

Defined in:
lib/attribute_fu/associations.rb

Instance Method Summary collapse

Instance Method Details

#has_many_with_association_option(association_id, options = {}, &extension) ⇒ Object

Behaves identically to the regular has_many, except adds the option :attributes, which, if true, creates a method called association_id_attributes (i.e. task_attributes, or comment_attributes) for setting the attributes of a collection of associated models.

It also adds the option :discard_if, which accepts a proc or a symbol. If the proc evaluates to true, the child model will be discarded. The symbol is sent as a message to the child model instance; if it returns true, the child model will be discarded.

e.g.

:discard_if => proc { |comment| comment.title.blank? }
  or
:discard_if => :blank? # where blank is defined in Comment

The format is as follows:

@project.task_attributes = {
  @project.tasks.first.id => {:title => "A new title for an existing task"},
  :new => {
    "0" => {:title => "A new task"}
  }
}

Any existing tasks that are not present in the attributes hash will be removed from the association when the (parent) model is saved.



111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/attribute_fu/associations.rb', line 111

def has_many_with_association_option(association_id, options = {}, &extension)
  unless (config = options.delete(:attributes)).nil?
    managed_association_attributes[association_id] = {}
    if options.has_key?(:discard_if)
      discard_if = options.delete(:discard_if)
      discard_if = discard_if.to_proc if discard_if.is_a?(Symbol)
      managed_association_attributes[association_id][:discard_if] = discard_if
    end
    collection_with_attributes_writer(association_id)
  end
  
  has_many_without_association_option(association_id, options, &extension)
end