Hi there, I’m using what I call static tables. Not sure if that is the
right term but static tables hold a fixed size of values. For example a
country table would hold all countries. In my person table I have a
link to the country table. Whenever I create a new person I have a drop
down list where the country can selected. That works fine. But when my
Person.create function is called all I have is the country’s name and
not the id. So my question is how can I get the id from the selection
list.
Here is the way my person controller class. I stripped it down to the
essentials.
class PersonController < ApplicationController
scaffold :person
def list
@people = Person.find( :all )
end
def new
@person = Person.new
@name = Name.new
@country = Country.new
@countries = Country.find( :all ).map { |g| [g.name] }
end
def create
@person = Person.new(params[:person])
@name = Name.new(params[:name])
@country = Country.new(params[:country])
Person.transaction do
@person.name = @name
@person.country = @country
@name.save!
@person.save!
redirect_to :action => 'list'
end
rescue ActiveRecord::RecordInvalid => e
@name.valid?
@country.valid?
render_action ‘new’
end
end
Here also my new.rhtml
New PersonNew Person
<% form_for :person, :url => { :action => :create } do |form| %>
<%= error_messages_for :person %>
<%= error_messages_for :name %>
<%= error_messages_for :country %>
<% fields_for :name do |n| %>
First: <%= n.text_field :first %>
Middle: <%= n.text_field :middle %>
Last: <%= n.text_field :last %>
<% end %>
<p>
<% fields_for :country do |c| %>
Country: <%= c.select( :name, @countries ) %>
<% end %>
</p>
<%= submit_tag 'Create' %>
<% end %>
I hope you can follow my chain of thoughts. Please ask if you’re not.
Thanks ahead,
Christian