Wx::Choice Items generated from lookup table, later need id's of choices

Hi,

I'm using ActiveRecord for db access.....

If I have a table, fruits, with fields ID, name; and values:

ID,Name
1,Apple
2,Orange
3,Banana

And another, people, with ID,name, fruit_id

And I populate a Wx::Choice with these by doing something like

@choice = Wx::Choice.new
Fruit.find(:all).each {|fruit| @choice.append(fruit)}

And then later I want to create a person:

fred = Person.create(:name => "Fred", :fruit_id => ???)

What do I put in place of the ??? ?

I could do Fruit.find_by_name(@choice.get_string_selection), which

works, but in a larger app could lead to lots and lots of lookups, and
in my particular case, wouldn’t work in some places as the thing
appended to the Choice is an amalgam of the database fields.

I could do (@choice.get_selection +1) but that looks a bit ugly, and

just seems wrong.

I *think* I could subclass Wx::Choice to something that stores the

ID as well as the text to display, but I can see dragons in the distance
that way…

What's my best option?

Anthony

I think I could subclass Wx::Choice to something that stores the
ID as well as the text to display, but I can see dragons in the distance
that way…

What’s my best option?

Caveat emptor… I don’t know WxRuby at all. However, the
documentation
(http://wxruby.rubyforge.org/doc/controlwithitems.html#ControlWithItems_append)
mentions a method:

Integer append(String item, Object clientData)

Parameters:
item - String to add.
clientData - Client data to associate with the item.

and a corresponding:

Object get_item_data(Integer n)

Parameters:
n - The zero-based position of the item.

So would this work?

@choice = Wx::Choice.new
Fruit.find(:all).each {|fruit| @choice.append(fruit, fruit.id)}

selected_fruit_id = @choice.get_item_data(@choice.get_selection)
fred = Person.create(:name => “Fred”, :fruit_id => selected_fruit_id)

Tom S. wrote:

What’s my best option?

Caveat emptor… I don’t know WxRuby at all. However, the
documentation (http://wxruby.rubyforge.org/doc/controlwithitems.html#ControlWithItems_append)
mentions a method:

Hi Tom,

That does indeed work. Fantastic.

I should have seen that myself, I am going to say I didn't, because

I only thought of “store the data within the control” thing as I was
writing the email. But hey live and learn!

Thanks

Anthony

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs