[Rails] (no subject)
dblack at wobblini.net
dblack at wobblini.net
Fri Feb 10 23:47:04 GMT 2006
Hi --
On Fri, 10 Feb 2006, Peter T Bosse II wrote:
> I am trying to populate a select() popup menu with all of the currently
> entered options from the database. My thinking is that I would search the
> database for all records, then call my "get_options" with the name of the
> field as an argument.
>
> def list
> @assets = Asset.find(:all)
> get_options(@assets,"asset_type")
> end
>
> private
> def get_options(items,field)
> @options = []
> items.each do |@item|
> @options << @item.field
> end
> @options = @options.sort.uniq
> end
>
> This doesn't work. However, if I replace:
>
> @options << @item.field
>
> with:
>
> @options << @item.asset_type
>
> (...where "asset_type" is the name of a field in the database) it does work.
> Now, I'm trying to follow the DRY principles, but I can't figure out how to
> pass the field name to "get_options". I could write a dozen or so
> "get_options_asset_type", "get_options_serial_number" and the like and it
> would work, but this is an opportunity for me to learn. How am I supposed to
> do this?
You can use send:
@options << @item.send(field)
You could tighten up the method a bit if you like (untested rewrite
follows):
def get_options(items,field)
@options = items.map {|item| item.send(field) }.sort.uniq
end
(I've changed @item to item as it wasn't clear why that would need to
be an instance variable.)
David
--
David A. Black (dblack at wobblini.net)
Ruby Power and Light (http://www.rubypowerandlight.com)
"Ruby for Rails" chapters now available
from Manning Early Access Program! http://www.manning.com/books/black
More information about the Rails
mailing list