Module: NestedStoreAttributes::AcceptsStoreAttributes::ClassMethods
- Defined in:
- lib/nested_store_attributes/accepts_store_attributes.rb
Constant Summary collapse
- REJECT_ALL_BLANK_PROC =
proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
Instance Method Summary collapse
-
#accepts_store_attributes_for(*attr_names) ⇒ Object
Defines an attributes writer for the specified serialized attribute(s).
Instance Method Details
#accepts_store_attributes_for(*attr_names) ⇒ Object
Defines an attributes writer for the specified serialized attribute(s).
Supported options:
- :allow_destroy
-
If true, destroys any members from the attributes hash with a
_destroykey and a value that evaluates totrue(eg. 1, ‘1’, true, or ‘true’). This option is off by default. - :reject_if
-
Allows you to specify a Proc or a Symbol pointing to a method that checks whether a record should be built for a certain attribute hash. The hash is passed to the supplied Proc or the method and it should return either
trueorfalse. When no :reject_if is specified, a record will be built for all attribute hashes that do not have a_destroyvalue that evaluates to true. Passing:all_blankinstead of a Proc will create a proc that will reject a record where all the attributes are blank excluding any value for _destroy. - :limit
-
Allows you to specify the maximum number of the nested records that can be processed with the nested attributes. Limit also can be specified as a Proc or a Symbol pointing to a method that should return number. If the size of the nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords exception is raised. If omitted, any number nested records can be processed.
- :primary_key
-
Allows you to specify the primary key to use when checking for existing objects. This defaults to :id.
Examples:
# creates subscribers_attributes=
accepts_store_attributes_for :subscribers, primary_key: :email
# creates books_attributes=
accepts_store_attributes_for :books, reject_if: proc { |attributes| attributes['name'].blank? }
# creates books_attributes=
accepts_store_attributes_for :books, reject_if: :all_blank
# creates books_attributes= and posts_attributes=
accepts_store_attributes_for :books, :posts, allow_destroy: true
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/nested_store_attributes/accepts_store_attributes.rb', line 56 def accepts_store_attributes_for(*attr_names) = { :allow_destroy => false, :update_only => false, :primary_key => :id } .update(attr_names.) .assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only, :primary_key) [:reject_if] = REJECT_ALL_BLANK_PROC if [:reject_if] == :all_blank attr_names.each do |attribute_name| if self.attribute_names.include?(attribute_name.to_s) = self..dup [attribute_name] = self. = store_generate_collection_writer(attribute_name) else raise ArgumentError, "No column found for name `#{attribute_name}'. Has it been added yet?" end end end |