Forms and one-to-one association


#1

My models are:

class Event < ActiveRecord::Base
belongs_to :location

class Location < ActiveRecord::Base
has_one :event

The view:


<%= datetime_select ‘event’, ‘meet_at’, :start_year => 2006 %>


<%= collection_select(:event, :location, @locations, :id, :name) %>

The problem is that in the controller, when I create a new event, it
says it expects a Location and not a string: “Location expected, got
String” in the “@event = Event.new(params[:event])” line.

I’m a bit confused…shouldn’t Rails have enough information to turn the
location ID into a full location, and actually, shouldn’t the ID be
enough in this case?

Thanks,

-elan


#2

Hi !

2006/1/27, Elan removed_email_address@domain.invalid:

<%= collection_select(:event, :location, @locations, :id, :name) %>

The problem is that in the controller, when I create a new event, it
says it expects a Location and not a string: “Location expected, got
String” in the “@event = Event.new(params[:event])” line.

I’m a bit confused…shouldn’t Rails have enough information to turn the
location ID into a full location, and actually, shouldn’t the ID be
enough in this case?

Change your collection select line to:
<%= collection_select(:event, :location_id, @locations, :id, :name) %>

Notice the field name ? You were assigning a String to a Location
instance. Now, you will be assigning to an attribute that expects a
Fixnum, and Rails will attempt to convert the Fixnum into a String, so
everything will be right.

Hope that helps !


#3

Thanks so much for your rapid reply!

-elan