How to validate a aray in model?

In form I have a multiple select option, that returns a array

(in model I convert array to string and save it to database)

array can only have values ['A','B','C','D','E','']

So how can I valdate that some value is not a X or Y ?

The model code is:


attr_accessor :categories

def categories
if self.category
@categories = self.category.split
else
@categories = ['']
end
end

def categories=(xxx)
@categories = xxx
return if xxx.blank?
self.category = xxx.join(" ")
end

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

Search Discussions

  • Dave Aronson at Dec 16, 2011 at 6:49 pm

    On Fri, Dec 16, 2011 at 13:30, Fresh Mix wrote:

    How to validate a aray in model?
    In form I have a multiple select option, that returns a array
    (in model I convert array to string and save it to database)
    array can only have values ['A','B','C','D','E','']
    So how can I valdate that some value is not a X or Y ?
    Use a custom validator method that looks at the elements. See:

    http://guides.rubyonrails.org/active_record_validations_callbacks.html#custom-validators

    and use an array of bad elements with a method like so:

    badElts = [:put, :bad, :element, :values, :here]

    def validate record
    record.array_of_stuff.each do |elt|
    record.errors[:name] << "'#{elt}' is forbidden" if badElts.include? elt
    end
    end

    -Dave

    --
    LOOKING FOR WORK! What: Ruby (on/off Rails), Python, other modern languages.
    Where: Northern Virginia, Washington DC (near Orange Line), and remote work.
    See: davearonson.com (main) * codosaur.us (code) * dare2xl.com (excellence).
    Specialization is for insects. (Heinlein) - Have Pun, Will Babble! (Aronson)

    --
    You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
    To post to this group, send email to rubyonrails-talk@googlegroups.com.
    To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
    For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouprubyonrails-talk @
categoriesrubyonrails
postedDec 16, '11 at 6:31p
activeDec 16, '11 at 6:49p
posts2
users2
websiterubyonrails.org
irc#RubyOnRails

2 users in discussion

Fresh Mix: 1 post Dave Aronson: 1 post

People

Translate

site design / logo © 2021 Grokbase