我有一个错误:在@subject = Subject.find(params [:subject_id])中找不到没有ID的主题 我创建了多对多关联。有三种模式 - 教师,主题和订阅。订阅模型包括以下字段:teacher_id和subject_id。
class Subject < ActiveRecord::Base
has_many :subscriptions
has_many :teacher, :through => :subscriptions
end
class Teacher < ActiveRecord::Base
has_many :subscriptions
has_many :subjects, :through => :subscriptions
end
class Subscription < ActiveRecord::Base
belongs_to :subject
belongs_to :teacher
end
teacher_controller
def create
@subject = Subject.find(params[:subject_id])
@teacher = Teacher.new(teacher_params)
respond_to do |format|
@teacher.subjects << @subject
if @teacher.save
format.html { redirect_to @teacher, notice: 'Teacher was successfully created.'
format.json { render action: 'show', status: :created, location: @teacher }
else
format.html { render action: 'new' }
format.json { render json: @teacher.errors, status: :unprocessable_entity }
end
end
end
_form.html.erb
<%= form_for(@teacher,:html => { class: 'login-form' }) do |f| %>
<%= f.fields_for :subject do |n| %>
<%= n.select(@subject, @subjects.map{|p| [p.name, p.id]}) %>
<% end %>
...
<% form %>
resources :teachers do
resources :subjects
end
答案 0 :(得分:1)
改为
def create
@subject = Subject.where("id =?", params[:subject_id]).first
unless @subject.blank?
@teacher = Teacher.new(teacher_params)
......
......
else
# set flash message and redirect
end
end
答案 1 :(得分:0)
在视图中,_form.html.erb,替换select_tag
<%= select_tag "subject_id", options_from_collection_for_select(@subjects, "id", "name") %>
在控制器代码中,
def create
@subject = Subject.where(id: params[:subject_id]).first
if @subject.present?
#YOUR CODE GOES HERE.
else
render 'new' # OR render to the action where your teacher form resides
end
end