Forum: Ruby on Rails Forms and one-to-one association

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.
Elan (Guest)
on 2006-01-28 01:29
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  %></p>
<%=	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
Francois B. (Guest)
on 2006-01-28 02:31
(Received via mailing list)
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 !
Elan (Guest)
on 2006-01-28 03:13
Thanks so much for your rapid reply!

-elan
This topic is locked and can not be replied to.