我正在尝试使用包含对自身引用的连接表为模型构建表单。 我会给你一个快速的例子,说明我想要实现的目标:
让我说我有主题物理。要学习物理,你需要知道基础数学,即物理学依赖于数学。任何主题都应该能够兼有多种依赖关系。 我遇到的问题是通过表格提交这种关系。
我的代码:
型号:
class Subject < ActiveRecord::Base
has_many :needs, foreign_key: :target_id
has_many :subjects, through: :needs
accepts_nested_attributes_for :needs,:subjects,allow_destroy: true
end
class Need < ActiveRecord::Base
belongs_to :target, class_name: :subject
belongs_to :prerequisite, class_name: :subject
end
控制器:
class SubjectsController < ApplicationController
def create
@subject = Subject.new secure_params
if @subject.save
redirect_to root_path, success: 'Subject created'
else
render :new
end
end
def new
@subject = Subject.new
end
private
def secure_params
params.require(:subject).permit(:name, :content, needs_attributes: [:target,:prerequisite])
end
end
表格:
<div class="row">
<div class="col-md-8">
<%= simple_nested_form_for @subject do |f| %>
<%= f.input :name %>
<%= f.input :content %>
<%= f.fields_for :needs do |d| %>
<%=d.association :prerequisite %>
<% end %>
<%= f.link_to_add "Add a prerequisite", :needs %>
<%= f.submit class: 'btn btn-primary btn-lg' %>
<% end %>
</div>
</div>
使用这种方法,我在进入“新”动作时得到“未初始化的常量Need :: subject”。 任何关于我的方法或代码中的错误的想法将不胜感激。 编辑:添加连接表
class CreateNeeds < ActiveRecord::Migration
def change
create_table :needs do |t|
t.references :target
t.references :prerequisite
end
end
end
Edit2:工作代码(仅更改了部分)
模型
class Subject < ActiveRecord::Base
has_many :needs, foreign_key: :target_id
has_many :prerequisites, class_name: "Subject",through: :needs, source: :prerequisites
accepts_nested_attributes_for :needs,:prerequisites,allow_destroy: true
end
class Need < ActiveRecord::Base
belongs_to :target, class_name: "Subject"
belongs_to :prerequisite, class_name: "Subject"
end
控制器
def secure_params
params.require(:subject).permit(:name, :content, needs_attributes: [:prerequisite_id])
end
end
答案 0 :(得分:0)
就像我在评论中所说的那样,在你担心表格之前,要注意确保所有关联都正确连接。控制台或自动化测试都是测试它的好地方。
我认为应该是这样的:
class Subject < ActiveRecord::Base
has_many :needs, as: :target
has_many :subjects, :class_name: "Subject", through: :needs, source: :prerequisite
accepts_nested_attributes_for :needs,:subjects,allow_destroy: true
end
#assuming you have fields target_id and prerequisite_id in this table
class Need < ActiveRecord::Base
belongs_to :target, class_name: :subject
belongs_to :prerequisite, class_name: :subject
end
我认为协会名称&#34;科目&#34;可能会引起混淆,因为它会返回此主题所需的主题。这对读者来说并不是显而易见的,将来可能包括你。
在某些时候,您可能希望列出需要此主题的主题。现在可能值得区分这些,所以你可以清楚地区分它们。你可以这样做:
class Subject < ActiveRecord::Base
has_many :required_needs, as: :target
has_many :required_by_needs, as: :prerequisite
has_many :required_subjects, :class_name: "Subject", through: :required_needs, source: :prerequisite
has_many :required_by_subjects, :class_name: "Subject", through: :required_by_needs, source: :target
accepts_nested_attributes_for :required_needs, :required_by_needs, :required_subjects, :required_by_subjects, allow_destroy: true
end