Forms and one-to-one association

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

Hi !

2006/1/27, Elan [email protected]:

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

Thanks so much for your rapid reply!

-elan

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs