autotheist
autotheist

Reputation: 13

Ruby On Rails - Can't pass an array to the options_to_select in select form tag

I'm trying to get options to display for my select tag by passing an array using a helper. I am new to ROR and I can't figure this out. I've been able to use my helper to pass in an array of the U.S. states but it won't take my array the way I've built it. I tested the function as a ruby program and it does indeed return the array that I've built but it's not working when I pass it to the options_for_select. There are no options displaying.

So here is my helper:

module ImagesHelper
    def get_images
       image_array = Array.new()
       Dir.glob("../assets/images/*.jpg") do |item|
          new = item.to_s
          new = new.slice(17..new.length)
          image_array << new
       end
      image_array
   end
end

The above creates an array of the names of jpg's in my images folder with the directory name cut off.

Here is the form code for my select tag:

<div class="field">
<%= f.label :imageurl %><br />
<%= f.select(:imageurl, options_for_select(get_images)) %>
</div>

I'm using Ruby 1.9.3 and Rails 3

Upvotes: 1

Views: 167

Answers (1)

TK-421
TK-421

Reputation: 10763

How about this?

module ImagesHelper
  def get_images
    image_array = Array.new()
    Dir.glob("app/assets/images/*.jpg") do |item|
      image_array << File.basename(item)
    end
    image_array
  end
end

This is tested with Rails 4, so you may have to fiddle more with the path, but I think this should do it.

Also note the use of File.basename so you don't have to count characters in the name (the method is less fragile this way).

An additional also: I wouldn't recommend using new as a variable name--even if there isn't a conflict occurring in this case, it's the sort of thing that can cause problems later. (Bugs like to sneak up on you when you're not looking.)

It can also be confusing to other programmers, to see so much new in the function.

Here's a list of Ruby and Rails reserved words:

http://www.rubymagic.org/posts/ruby-and-rails-reserved-words

Upvotes: 0

Related Questions