1

This seems like it should be in Rails A1, but I can't find it any where. I have a bunch of locations stored in a Location table, made up of text fields City, County, Country etc. (This should have all been normalised out in my opinion, but there you go...).

A user can search by Location, and they enter into the separate search fields. At the moment, I'd like the Country such box to be a drop down list of countries. I currently get the list of countries in the db as follows:

@countries = Location.find(:all, :select=>"DISTINCT country")

The search box is currently just a text field:

<%= f.text_field :country,{:placeholder => "Country",:size=>20 } %>

But I'd like that to be a drop down box of the countries that are already in the @countries variable. It will just pass the country as a string. I'm a complete Newbie to Rails and even the basics are flumaxing me...Help!

1 Answer 1

2

If name is the actual name of the county in your country model:

 <%= f.select(:country, @countries.map(&:name), {:include_blank => 'Select a Country'}) %>

You could do differently, having the value of the field different from the value displayed. Documentation lives here.

FYI, I usually use a very convenient gem named Carmen to handle country lists etc...

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your comment. It's a Location model rather than a Country model, so I'm pulling out a list of distinct country fields into an array. So with a slight amendment to change (&:name) to (&:country) it worked!. I will definitely take a look at your Gem, as my who Location model this is just wrong!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.