lundi 18 mars 2019

undefined method `id' for "":String

I am trying to save has_one through rails form. I have a class

class Org
  has_one :org_name
  has_one :org_type, through: :org_name
end

and this is my form field for saving org

= f.select 'org_type', OrgType.order('name').collect { |t| [t.name, t.id] }, { include_blank: true }, class: 'data_field'

when I am saving record without selecting org_type it throws an error

NoMethodError - undefined method `id' for "":String:
(gem) activerecord-3.1.12/lib/active_record/associations/through_association.rb:47:in `block in construct_join_attributes'

at below line means during initialization. My org model already has this validation validates_associated :org_type

@org = Org.new(params[:org])

I am using rails 3.1.12. How can I validate has_one relation and throw a custom error message.

Aucun commentaire:

Enregistrer un commentaire