Co2
Co2

Reputation: 353

Ruby on Rails: ActiveRecord::AssociationTypeMismatch

I am getting an ActiveRecord::AssociationTypeMismatch error when trying to submit a record.

Subject(#88982676) expected, got String(#20223000)

View:

<%= f.collection_select :subject, Subject.order(:subject), :subject, :subject, {prompt: "Select a subject"}, {class: "form-control"} %>

Controller:

 def create
            @homework = current_user.homeworks.build(homework_params)
            if @homework.save
                redirect_to homeworks_path
            else
                render 'new'
            end
        end
...

def homework_params
            params.require(:homework).permit(:subject, :description, :date, :completed_at)
        end

Model: Homework.rb

class Homework < ActiveRecord::Base

 validates :subject, presence:true

    belongs_to :subject

def completed?
    !completed_at.blank?
end


end

Subject.rb

class Subject < ActiveRecord::Base

     has_many :homeworks

     def to_s
     subject
  end
end

This use to work but suddenly doesn't. I did change the name of the table to "subject" and changed the views and controller accordingly. It appears to be looking for id now? Subject is a string. Any advice? Thanks.

Upvotes: 0

Views: 93

Answers (1)

pyfl88
pyfl88

Reputation: 1710

According to your association models, your homework attributes should look like this:

subject_id:integer description:string date:datetime completed_at:datetime

Therefore, you should permit subject_id, instead of subject in your homework_params

As for collection_select method, it should be something like this:

f.collection_select :subject_id, Subject.order(:subject), :id, :subject

Upvotes: 1

Related Questions