# Selection field using foreign key (Multiple references)

**URL:** <https://www.ruby-forum.com/t/selection-field-using-foreign-key-multiple-references/125659>\
**Category:** Rails\
**Created:** [January 11, 2008, 12:54am UTC](https://www.ruby-forum.com/t/selection-field-using-foreign-key-multiple-references/125659 "2008-01-11T00:54:38Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![theclayman](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8e8cbc/32.png) [@theclayman](https://www.ruby-forum.com/u/theclayman)\
**Post date:** [January 11, 2008, 12:54am UTC](https://www.ruby-forum.com/t/selection-field-using-foreign-key-multiple-references/125659/1 "2008-01-11T00:54:38Z")

</div>

Hi,

after hours of trying I am stuck with the following. I have a Class for  
courses (called GdFb here) with multiple references to Class GdPerson

class GdFb \< ActiveRecord::Base  
belongs\_to :va\_plan,  
:foreign\_key =\> “va\_plan”,  
:class\_name =\> “GdPerson”

belongs\_to :va\_org,  
:foreign\_key =\> “va\_org”,  
:class\_name =\> “GdPerson”

and a Class for Persons:

class GdPerson \< ActiveRecord::Base  
has\_many :gd\_fbs  
end

Now I want selection fields that allow me to edit the fields va\_plan and  
va\_plan by selecting from existing entries in the GdPerson-Table.

I have tried many code snippets like  
\<% @personen = GdPerson.find(:all).collect { |c| [c.name, c.id] } %\>  
\<%#= collection\_select(‘gd\_fb’, ‘va\_plan’, @personen, :id, :name, {},  
:multiple =\> false) %\>

But none of them worked. Can someone help?

TIA

---

<div class="post-metadata">

**Author:** ![theclayman](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8e8cbc/32.png) [@theclayman](https://www.ruby-forum.com/u/theclayman)\
**Post date:** [January 11, 2008, 2:27pm UTC](https://www.ruby-forum.com/t/selection-field-using-foreign-key-multiple-references/125659/2 "2008-01-11T14:27:24Z")

</div>

…finally I figured it out: The Parameter for belongs\_to _must not_  
have the same name as for “foreign\_key”

Classfiles now contain:

class GdFb \< ActiveRecord::Base  
belongs\_to :va\_plan,  
:foreign\_key =\> “va\_plan\_id”,  
:class\_name =\> “GdPerson”

class GdPerson \< ActiveRecord::Base  
has\_many :gd\_fbs

The migration files:

class CreateGdFbs \< ActiveRecord::Migration  
def self.up  
create\_table :gd\_fbs do |t|  
t.column :va\_plan\_id, :integer

class CreateGdPeople \< ActiveRecord::Migration  
def self.up  
create\_table :gd\_people do |t|  
t.column :name :string

Creating a selection list that updates the foreign-key relation  
correctly works this way:

\<%= f.collection\_select(:va\_plan\_id, GdPerson.find(:all), :id, :name,  
{:prompt =\> true}) %\>
