尝试创建新学生时遇到错误:未找到关联:subject_item
有错误的文件是app/views/students/_form.haml
:
= simple_form_for student do |f|
= f.input :first_name
= f.input :last_name
= f.association :subject_items, label_method: :title, value_method: :id, label: 'Subject Items', as: :check_boxes
= link_to t('shared.back'), students_path, class: 'btn btn-default'
= f.button :submit
型号:
class Student < ActiveRecord::Base
has_many :participations, dependent: :destroy
has_many :subject_item_notes, dependent: :destroy
validates :first_name, :last_name, presence: true
end
路线:
Rails.application.routes.draw do
devise_for :users
resources :students do
get :subjects
end
resources :teachers do
get :subjects
end
resources :reports do
get :subjects
end
resources :visitors
resources :subject_items
root to: 'students#index'
end
我在这里缺少什么?
答案 0 :(得分:0)
您遇到的问题是,当关联不存在时,您正在调用f.association :subject_items
。
它应该看起来类似于:
#app/models/student.rb
class Student < ActiveRecord::Base
has_many :subject_items
end
我看到的另一个问题是您要添加check_boxes
来选择各种has_many
相关记录...
您的实施无效 - f.association
仅适用于has_many :through
或has_and_belongs_to_many
(IE many-to-many
)。
您当前的设置需要创建关联的记录,以便选择&#34;选择&#34;他们为你student
;您需要的是能够根据需要将它们关联在一起。
我会做以下事情:
#app/models/student.rb
class Student < ActiveRecord::Base
has_and_belongs_to_many :subjects
end
#app/models/subject.rb
class Subject < ActiveRecord::Base
has_and_belongs_to_many :students
end
#join table = students_subjects subject_id | student_id
这将允许您使用f.association
输入,如下所示:
= simple_form_for student do |f|
= f.input :first_name
= f.input :last_name
= f.association :subjects, label_method: :title, value_method: :id, label: 'Subject Items', as: :check_boxes
= link_to t('shared.back'), students_path, class: 'btn btn-default'
= f.button :submit
作为次要说明,您还需要在原理图中更新一些其他内容。
<强> 1。路由强>
#config/routes.rb
root to: 'students#index'
resources :visitors, :subject_items
resources :students, :teachers, :reports do
resources :subjects, only: :index
end
您可以使用Rails路由中的multiple resource definitions大幅提高路由定义的效率。
我刚刚测试过,您可以将嵌套资源添加到这些路线中。
-
<强> 2。模型强>
在我上面的推荐中,我使用了has_and_belongs_to_many
关联。
这优先于has_many :through
,但如果您不在您的联接模型中包含任何关联数据,则会获得类似的结果。
您可能拥有此类数据 - &#34; subject_items&#34; - 在这种情况下,建议您使用has_many :through
关系。
如果你需要,我可以更新答案; Rails文档很好地解释了why you'd favour one over the other。
简而言之,我要说您应该将notes
保留在加入模式中(&#34;参与&#34;):
#app/models/student.rb
class Student < ActiveRecord::Base
has_many :participations #-> equivalent to "classes"
has_many :subjects, through: :participations
end
#app/models/participation.rb
class Participation < ActiveRecord::Base
#columns id | subject_id | student_id | notes | created_at | updated_at
belongs_to :student
belongs_to :subject
end
#app/models/subject.rb
class Subject < ActiveRecord::Base
has_many :participations
has_many :students, through: :participations
end