我在尝试提交记录时收到ActiveRecord :: AssociationTypeMismatch错误。
主题(#88982676)预期,得到字符串(#20223000)
查看:
<%= f.collection_select :subject, Subject.order(:subject), :subject, :subject, {prompt: "Select a subject"}, {class: "form-control"} %>
控制器:
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
模型: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
这种用途可以起作用,但突然之间却没有。我确实将表的名称更改为“subject”,并相应地更改了视图和控制器。它似乎正在寻找id?主题是一个字符串。有什么建议?感谢。
答案 0 :(得分:1)
根据您的关联模型,您的家庭作业属性应如下所示:
subject_id:integer description:string date:datetime completed_at:datetime
因此,您应该在subject_id
subject
而不是homework_params
至于collection_select方法,它应该是这样的:
f.collection_select :subject_id, Subject.order(:subject), :id, :subject