putting options for select list in model

10 views
Skip to first unread message

fugee ohu

unread,
Apr 30, 2018, 5:07:43 AM4/30/18
to Ruby on Rails: Talk
I've been putting options for select lists in my models but I haven't been able to do this with option/value pairs Anyone know how? The code below doesn't work

  DURATION_TYPES =  [['7 days', '7' ],['14 days', '14'], ['21 days','21'], ['30 days','30']]
  validates :duration, inclusion: { in: DURATION_TYPES }

Walter Lee Davis

unread,
Apr 30, 2018, 8:49:20 AM4/30/18
to rubyonra...@googlegroups.com
When this validator runs, what is it comparing? The label or the value? You are passing a combination of the two into your validator and expecting it to guess. You could try either using a hash for the data structure, and being explicit about what you want it to compare:

DURATION_TYPES = {'7 days' => 7, '14 days' => 14 ... }
validates :duration, inclusion: { in: DURATION_TYPES.values }

or you could extract just the second value out each pair (using your existing nested array):

validates :duration, inclusion: { in: DURATION_TYPES.map(&:last) }

Please google "Ruby symbol to Proc" to better understand how that last one works. If you use the first approach, then you will need to change the way you access the constant's values in your select list constructor.

Walter

> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
> To post to this group, send email to rubyonra...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/c04d58fa-0e5b-42f8-8d80-20375f07f98c%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Message has been deleted

fugee ohu

unread,
May 2, 2018, 3:37:17 PM5/2/18
to Ruby on Rails: Talk
This simpler use causes the same 'not included in the list' error

  DURATION_TYPES = ['7 days', '14 days'] 
  validates :duration, inclusion: DURATION_TYPES
 
Reply all
Reply to author
Forward
0 new messages