Consider including DataMapper hack to coerce empty Strings to nil, for Integer properties #916

Closed
postmodern opened this Issue Aug 23, 2012 · 8 comments

Projects

None yet

4 participants

@postmodern
Contributor

When submitting forms that include foreign-key values (foo_id=1), DataMapper is unable to coerce an empty String (the default value of a form field) to nil. Instead, DataMapper complains that the foreign-key must be nil or an Integer. As a work-around, I use this monkey-patch to DataMapper::Property::Integer:

module DataMapper
  class Property
    class Integer

      def typecast_to_primitive(value)
        # filters out empty Strings for properties that allow nil
        unless (allow_nil? && value.blank?)
          typecast_to_numeric(value,:to_i)
        end
      end

    end
  end
end

See also: datamapper/dm-rails#27

@jasonseney

Agreed, this really caused me a headache when trying to implement optional associations.

@ujifgc
Member
ujifgc commented Jan 12, 2013

typecast_to_primitive is removed from DataMapper 1.3.

@dariocravero
Member

dm-core said it's not a core issue and they were going to fix that on dm-rails but it looks like nothing has happened with it. Perhaps we should ask there again?

@ujifgc
Member
ujifgc commented Jan 12, 2013

Are we protected from mass assignment in any way? These issues should be resolved together.

@ujifgc
Member
ujifgc commented Jan 12, 2013

Should we plan this for 1.0 or close as #905 is there to protect from mass assignment. I think disallowed params should be deleted and good ones cast to integers or nils.

@dariocravero
Member

Good call @ujifgc. Rescheduled it for 1.0.

@ujifgc
Member
ujifgc commented Aug 4, 2014

Closing in favor of #1524.

Also you can use params protection to typecast foreign keys:

post :update, :params => [:name, :foreign_model_id => Integer] do
@ujifgc ujifgc closed this Aug 4, 2014
@postmodern
Contributor

@ujifgc too cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment