Hi all
I tried and tried and tried, but I still fail in creating a form with
proper validation and stuff for foreign keys… So I’d really like to
get some help here.
I’m creating a booking site for DJ’s, and for every booking one can
choose one of different countries:
class Booking < ActiveRecord::Base
validates_presence_of :country_id
validates_numericality_of :country_id # Necessary? Correct???
belongs_to :country,
:dependent => true
end
class Country < ActiveRecord::Base
has_many :countries
end
Now I have created a scaffold of the bookings, but sadly this does not
include the wanted select box for country selection. So I added it
myself:
<%= error_messages_for ‘booking’ %>
<%= start_form_tag :action => ‘new’ %>
Country: <%= collection_select(:booking, :country, @countries, :id,
:name, :include_blank => true) %>
<%= end_form_tag %>
So far, so good, the countries are well displayed in a select box. But
when I submit the form, I get the following error:
ActiveRecord::AssociationTypeMismatch in BookingsController#new
Country expected, got String
RAILS_ROOT: /Users/Josh/Webwork/psyguideorg/public/…/config/…
Application Trace | Framework Trace | Full Trace
/Applications/Locomotive2/Bundles/rails112.locobundle/powerpc/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/associations/association_proxy.rb:134:in
raise_on_type_mismatch' /Applications/Locomotive2/Bundles/rails112.locobundle/powerpc/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/associations/belongs_to_association.rb:22:inreplace’
/Applications/Locomotive2/Bundles/rails112.locobundle/powerpc/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/associations.rb:850:in
country=' /Applications/Locomotive2/Bundles/rails112.locobundle/powerpc/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/base.rb:1510:inattributes=’
/Applications/Locomotive2/Bundles/rails112.locobundle/powerpc/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/base.rb:1509:in
attributes=' /Applications/Locomotive2/Bundles/rails112.locobundle/powerpc/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/base.rb:1354:ininitialize_without_callbacks’
/Applications/Locomotive2/Bundles/rails112.locobundle/powerpc/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/callbacks.rb:236:in
initialize' #{RAILS_ROOT}/app/controllers/bookings_controller.rb:27:innew’
Can anybody tell me what to do? Do I have to add some sort of
before_validation method that creates the Country object instead of the
String (which is the ID of the selected country)?
Thanks very much for help.
Joshua
