Displaying foreign keys help request


Hi …

(I seem to be having some problems getting my posts to the list for some
reason. Sorry if you see this as a repost).

A conceptual question this time.

I have the relation:

member (m)---(1) member_type

The schema looks something like this (simplified + PGSQL)

create table member_types (
id serial,
info varchar( 20 ) not null,
primary key( id )

create table members (
id serial,
first_name varchar( 100 ) not null,
last_name varchar( 100 ) not null,
email varchar( 100 ) not null,
member_type_id integer not null,
primary key( id ),
constraint fk_m_member_type foreign key( member_type_id )
references member_types( id )

And in the model:

class Member < ActiveRecord::Base
belongs_to :voice_type
# validation stuff removed

My question is that I want to add a new member, with the member_types as
a select list. Obviously, when I add the member to the database, I will
want to add the id, rather than the actual member_type.

In app/views/admin/new.rhtml, I have this (snippet from table add):

@mt = MemberType.find( :all, :order => "info" )
select( :member_type_id, :member_type, @mt )

Which returns the correct number of rows, but of Object IDs, rather than
the info strings.

Clearly I haven’t got it right. I am pretty sure that this would be a
FAQ, though I am not able to find anything that directly answers this
type of question.

Any help appreciated.


Mark Probert probertm at acm dot org


Mark Probert wrote:

@mt = MemberType.find( :all, :order => “info” )
select( :member_type_id, :member_type, @mt )
The select methods actually takes an array of 2-member lists, just like
you’d get if you did a Hash#to_a call. This may work for you:

@mt = MemberType.find(:all, :order => “info”)
select( :member, :member_type_id, @mt.collect{|t| [t.info, i.id]} )

This is documented at