-
Notifications
You must be signed in to change notification settings - Fork 229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Distinguish empty arrays from an unset attribute #334
Comments
You can do |
Thanks for your reply. I tried that just now. So no extras were passed into the Virtus model, |
@michaelimstepf I'm having the same issue. Did you find a solution to this? |
@forest Sorry, pls ignore previous comment (deleted), I was referring to a different issue. Can you try this: class UpdateForm
include Virtus.model(nullify_blank: true)
include ActiveModel::Model
attribute :extras, Array
attribute :booking_time, Time
def initialize(opts={})
super
# http://stackoverflow.com/a/31959720/1076279
@extras = nil unless opts['extras'].present?
end
def save
some_object.update(updatable_attributes)
end
end |
@michaelimstepf thanks for the reply. If I just needed this for one attribute on one class I'd go this route. I opted for this https://gist.github.com/657fd558a9c05416cf81 temporary solution until #209 lands on master so I can create my own attribute extension. It is odd to me that |
Thanks for posting this |
This (kind of) worked for me: But ;-) If you look at the use case "I want to be able to distinguish nil from empty", I don't think any of the currently suggested solutions/workarounds are totally fitting:
I would expect that specifying Since nil gets coerced to an empty Array by the coercer, maybe the code to adapt is Virtus::Attribute::Coercible#set, like this:
(edit:) With this change, setting I can make a PR and write some tests if that's an acceptable solution, what do you think? |
@mherold your analysis and solution sounds right. I knew changing I'm happy to test with my use case when you push up the PR. |
Thanks @forest, I appreciate it!! PR is available. |
@forest awesome, thanks for testing! |
@forest we have such hack in our app either. It would be great to have it merged. |
I have several forms that submit to a Virtus object (through a controller). Some forms contain an
extras
attribute, others don't.I currently can't distinguish whether
extras
has been set to an empty array (i.e. the user deselects all checkboxes on the form) or whether extras has never been submitted. In either case,extras
will be an empty array.I need this distinction because if the user deselects all
extras
I need to update them. On the other hand, if extras were not part of the form (i.e. not in the params), I shouldn't update them.How can I make Virtus to give me a nil on
extras
if I call it like this:Or is there a better pattern to do this?
The text was updated successfully, but these errors were encountered: