Forum: Ruby on Rails Problem with selection lists

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
chhenning (Guest)
on 2007-01-24 18:04
(Received via mailing list)
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

<html>
<head>
<title>New Person</title>
</head>

<body>
<h1>New Person</h1>

    <% 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 %>

<a href="/person/list">Back</a>

</body>
</html>

I hope you can follow my chain of thoughts. Please ask if you're not.

Thanks ahead,
Christian
Jason S. (Guest)
on 2007-01-24 19:45
(Received via mailing list)
Hi,

Try using collection_select.

Get your countries like this instead of mapping just the name to a new
collection:
@countries = Country.find(:all)

Then this in your view (assuming your foreign key is country_id):
<%= c.collection_select(:country_id, @countries, "id", "name")  %>


Jason

On Wed, 24 Jan 2007 16:02:51 -0000
This topic is locked and can not be replied to.