Ask A Question

Notifications

You’re not receiving notifications from this thread.

ActiveRecord AssociationType Mismatch

shakycode asked in Rails

I have a Rails 3.2.21 app where I'm adding a simple form/collection_select field in my form. When selecting an object from the dropdown (or leaving it blank) I get the following error:

ActiveRecord::AssociationTypeMismatch at /calls/5
BillFacility(#70179530126460) expected, got String(#70179505820040)

Here's what my models look like:

call.rb

    belongs_to :bill_facility
    attr_accessible :bill_facility_id

bill_facility.rb

    has_many :calls

Here's what my form looks like:

_form.html.erb

    <%= f.collection_select(:bill_facility_id, BillFacility.order("facility_name ASC"), :id, :facility_name, {:include_blank => true}, {:class => 'select'}) %>

Here's the migrations I did to add the BillFacility model and add the bill_facility_id to the Call model:

class CreateBillFacilities < ActiveRecord::Migration
  def change
    create_table :bill_facilities do |t|
      t.string :facility_name
      t.string :facility_address

      t.timestamps
    end
  end
end

class AddBillFaciltyIdToCalls < ActiveRecord::Migration
  def change
    add_column :calls, :bill_facility_id, :integer
  end
end

If I manually assign the call an id in bill_facility_id I get an unknown to_i method error. If I manually make it nil then select a BillFacilty from the drop down (or leave it blank) I get the mismatch error:

`ActiveRecord::AssociationTypeMismatch at /calls/5
BillFacility(#70179530126460) expected, got String(#70179505820040)`

I'm sure this is something simple that I'm missing. Anyone have any ideas on what I'm doing wrong here? It's a bit early so my mind is kind of fuzzy so I should probably wait until I'm fully awake but figured I'd ask for some help.

If you have any questions, please let me know.

Reply

I think I have this figured out. Definitely not awake enough to be writing code.

I had this in my form before the BillFacility collection_select

<%= f.label :Bill_Facility, "Bill Facility", class: "control-label" %><%= f.check_box :bill_facility, :id => 'bill_facility_checkbox' %>

So I was calling a field named bill_facility that was in my database, but since bill_facility is an associated model, it gave me the mismatch error. So I simple altered the migration to change the check_box to bill_fac and it worked.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,160+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.