Reputation: 102
I have an application that has three models: company
, university
and formation
.
Relations between these three models are:
class Company < ActiveRecord::Base
has_many :formations, dependent: :destroy
end
class University < ActiveRecord::Base
has_many :formations, dependent: :destroy
end
class Formation < ActiveRecord::Base
#company
belongs_to :company
#universities
belongs_to :university
def company_name
(company or university).try(:name)
end
def company_name=(name)
company_or_university = University.where(name: name).first
company_or_university ||= Company.where(name: name).first_or_create
self.company = company_or_university
end
end
So in this application I want to dropdown a list of universities and companies in the same field for formation form that is why I'm using this code in my formation form:
<% companies_or_universities = (Company.all.pluck(:name) + University.all.pluck(:name)).sort %>
<%= f.text_field :company_name, data: {autocomplete_source: companies_or_universities}, required: true, class: "form-control form-newjob" %>
this code works fine, but the problem is when I try to create a new formation and chose university name, I'm getting this error
Company(#-650866168) expected, got University(#-647908008)
for self.company = company_or_university
. How can I resolve this problem?
Upvotes: 1
Views: 57
Reputation: 10796
I think the error is quite explanatory: you cannot use a Company
association to store a University
, since the expected object is a Company
.
I believe that you'll get the result you are looking for if you rewrite your setter like this:
class Formation < ActiveRecord::Base
def company_name=(name)
university_from_name = University.where(name: name).first
if university_from_name
self.university = university_from_name
self.company = nil if persisted?
else
self.company = Company.where(name: name).first_or_create
self.university = nil if persisted?
end
end
end
As a side note, I think this implementation may be improved by using a polymorphic association instead of plain associations and custom setter and getter methods.
Upvotes: 1