Kelly
Kelly

Reputation: 469

Selecting Range by Database Attribute for Rails Form

Is it possible to select a range where the maximum number option is pulled from the database? I have this code below but it only gives 1 as an option. I'd like it to give the options 1 through the @item.quantity.

<%= f.select(:quantity_requested, [[email protected]], {}, { class: 'item-quantity form-control' }) %>

All other examples I see are of hard coded numbers. I would appreciate any help as to understanding why this doesn't work.

Thanks!

Upvotes: 0

Views: 125

Answers (1)

creativereason
creativereason

Reputation: 1524

I've never seen Ruby's range with dynamic numbers. I just tried doing it in irb and it didn't work correctly. Another alternative would be to use something like this (not tested, but idea is):

<%= f.select(:quantity_requested, 1.upto(quantity.times).to_a, {}, { class: 'item-quantity form-control' }) %>

Edit: I just tried this in an irb console and it started at zero based, so you'll want to use upto instead of times, see output below:

a = 100
a.times.to_a
=> [0, 1, ... 99]

1.upto(a).to_a
=> [1, 2, 3,.. 99, 100]

Upvotes: 1

Related Questions