How to correctly use collection_select along with

2019-09-03 03:55发布

问题:

I've got a patient profile mode like this:-

class Profile < ActiveRecord::Base
  belongs_to :eyes, class_name: "EyeColor", foreign_key: "eyes"
end

the database table has an integer called eyes

I have an EyeColor model which simply has an ID and Description (text for the colour)

and I've made a form which has a collection_select on it like this:-

<div class="field">
    <%= f.label :eyes %><br>
    <%= f.collection_select :eyes, EyeColor.all, :id, :description  %>
</div>

now when I attempt to update the record via the form, I get the following:-

ActiveRecord::AssociationTypeMismatch (EyeColor(#45428760) expected, got String(#19387428))

I'm sure it's something simple, but any ideas what I have done wrong?

回答1:

The problem here is that the form structure will look for an :eyes attribute and assign it the string value the select will send for it. But the Rails engine is expecting an EyeColorobject for this attribute, not a String. You should change the name of your foreign key:

belongs_to :eye, class_name: "EyeColor", :foreign_key: "eye_id"

or better:

belongs_to :eyecolor

With this, you need a table named eye_colors, a class named EyeColor, and a foreign key eye_color_id.

Question already asked by the way:

https://stackoverflow.com/a/13356481/2943357

Hope this helps.