Moose
Moose

Reputation: 119

Association Type Mismatch

I am getting this error:

ActiveRecord::AssociationTypeMismatch (Design(#2199041060) expected, got String(#2151988680))

I am trying to create an Event whereby the user enters some information for the event and at the same time selects a Design. Each time I click on the Create button the error happens.

Here are my models:

class Design < ActiveRecord::Base  
  belongs_to  :event        # User creates an Event and selects only one Design
  belongs_to  :user         # User could also create a Design 
end

class Event < ActiveRecord::Base
  belongs_to  :user     # A user can create as many events
  has_one     :design   # User can only select one design for this event
end

Here is my Event Controller

def create
  @event = Event.new(params[:event])
  @user = current_user
  @designs = Design.all

  if @event.save
    flash[:success] = "Event created"
    @user.events << @event 
    redirect_to events_path
  end
end

Here is my Event View:

<%= form_for @event, :url => {:action => 'create', :id => @event.id } do |e| %>
<p>Enter a title for this event: <%= e.text_field :title %> </p>

<p>Select a design:</p> 
 <ul class = "list">
    <% @designs.each do |design| %>
        <li><%= e.radio_button :design, design.id %> <%= design.name %></li>
    <% end %>
 </ul>
    <%= e.submit "Create" %>
<% end %>

Upvotes: 1

Views: 4242

Answers (2)

Taryn East
Taryn East

Reputation: 27747

<%= e.radio_button :design, design.id %>

You're not actually passing a whole design object to your event model - just the id, so this should actually reflect that by instead using:

<%= e.radio_button :design_id, design.id %>

Edit: and add to your event model:

def design_id=(the_id)
  return unless the_id
  the_design = Design.find_by_id(the_id)
  self.design = the_design if the_design
end

Upvotes: 1

David Grayson
David Grayson

Reputation: 87406

In your view, change :design to :design_id.

Upvotes: 2

Related Questions