Forum: Ruby on Rails Add value to select box

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Alex J. (Guest)
on 2008-10-26 23:29
(Received via mailing list)
Hey guys!

I was wondering. I'm generating a select box in my view where the user
can pick from a number of alternatives. However, I would like the last
option to be "Add new..." and then a box would pop up allowing the
user to enter a new value.

Now I've got all the JavaScript and the Rails code to allow the user
to enter a new option, the problem is how do I add the last
alternative ("Add new...") to my select box?

Take care!
Alex
Mikel L. (Guest)
on 2008-10-27 00:27
(Received via mailing list)
> Now I've got all the JavaScript and the Rails code to allow the user
> to enter a new option, the problem is how do I add the last
> alternative ("Add new...") to my select box?

In your controller:

@options = Option.find(:all).collect {|p| [ p.name, p.id ] }
@options << ["Add New", nil]

Then in your view:

<%= select("user", "choice_id", @options, { :include_blank => true })
-%>


This should work, because select just iterates over an array taking
the .first and .last values from it.

Mikel


--
http://lindsaar.net/
Rails, RSpec and Life blog....
Bill W. (Guest)
on 2008-10-27 01:57
(Received via mailing list)
Hi Alex,
>
>  However, I would like the last option to be "Add new..."
> and then a box would pop up allowing the user to enter a
> new value.
>
> Now I've got all the JavaScript and the Rails code to allow
> the user to enter a new option, the problem is how do I add
> the last alternative ("Add new...") to my select box?

Assuming that the action that adds the new option creates a new record
in
the db and that you're rendering a partial to display the select in the
first place (if not, refactor), just add a find to your action and
re-render
the select via RJS.

HTH,
Bill
This topic is locked and can not be replied to.