我有以下模型,它们基本上试图表示教授具有特定水平的许多科目的知识。科目是固定的,因此不会创建新科目,只会通过知识连接表与教授“相关”。
class Subject < ActiveRecord::Base
# Self Associations
has_many :subcategories, :class_name => "Subject"
belongs_to :category, :class_name => "Subject",:foreign_key => "parent_id"
# Associations
has_many :knowledges
has_many :professors, :through => :knowledges
end
class Professor < ActiveRecord::Base
# Associations
has_many :knowledges
has_many :subjects, :through => :knowledges
...
end
class Knowledge < ActiveRecord::Base
# Associations
belongs_to :professor
belongs_to :subject
has_one :level
attr_accessible :subject_id, :professor_id
validates :subject_id, :uniqueness => { :scope => :professor_id }
end
我想要一个表格,让教授在他的帐户中添加一个主题,我决定有一个知识表格(因为我也希望能够插入一个级别)。
它看起来像这样:
<%= simple_form_for @knowledge,:url => professor_knowledges_path, :html => { :class => 'form-horizontal' } do |f| %>
<div class="control-group select optional">
<%= label_tag "Subject Type", nil, :class => "select optional control-label"%>
<div class="controls">
<%= select_tag "Parent Subject", options_from_collection_for_select(@parent_subjects, "id", "name"), :id => "knowledge_parent_subject" %>
</div>
</div>
<%= f.input :subject_id, :collection => @subjects, :label => "Subject" %>
<%= f.input :level %>
<%= f.button :submit, t('add_form'),:class => 'btn-primary' %>
<% end %>
在知识控制器的创建操作中,我有这个:
def create
@knowledge = Knowledge.create(:professor_id => current_professor.id, :subject_id => params[:knowledge][:subject_id])
end
我想/期望得到一个ActiveRecord说这个知识不能被插入,因为有一个唯一性违规,但是不,我只是在日志中看到一个 500 和一个回滚,但似乎执行仍在继续。所以我的问题是:我做错了什么,或者我该如何改善这种建模情况?我相信表单需要与连接模型相关,因为我希望在其上包含该模型的字段......但也许我错了,我可以用一种简单/更清洁的方式来做。
编辑:
正如其中一条评论所要求的,这里是表单提交的日志和回滚后的 500 错误:
Started POST "/professors/1/knowledges" for 127.0.0.1 at 2012-07-01 00:45:39 -0700
Processing by KnowledgesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"4JVyxWnIh37kyBwLwLGTHk/znsI1c5wrJvaWjKKT5tM=", "Parent Subject"=>"1", "knowledge"=>{"subject_id"=>"1"}, "commit"=>"Añadir", "professor_id"=>"1"}
Professor Load (0.4ms) SELECT `professors`.* FROM `professors` WHERE `professors`.`id` = 1 LIMIT 1
Completed 500 Internal Server Error in 4ms
我在创建操作中添加了一些条件,如下所示:
def create
@knowledge = Knowledge.new(:professor_id => current_professor.id, :subject_id => params[:knowledge][:subject_id])
if @knowledge.save
flash[:notice] = "Success..."
redirect_to professor_path(current_professor)
else
render :action => 'new'
end
end
这实际上在 500 之后显示以下内容:
Completed 500 Internal Server Error in 6ms
ActiveRecord::RecordInvalid (Validation failed: Subject has already been taken):
我想知道为什么会引发异常,而不是仅仅将错误添加到对象中并让我管理这种情况。以下行不应该做什么?
validates :subject_id, :uniqueness => { :scope => :professor_id }