我有一个错误:在@subject = Subject.find(params:subject_id)中找不到没有ID的Subject
我建立了多到多的联系。有三种模式:教师模式、学科模式和订阅模式。订阅模型包括以下字段: 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
endteacher_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发布于 2014-04-15 04:53:17
代之而行
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发布于 2014-04-15 04:57:27
在视图_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
endhttps://stackoverflow.com/questions/23074891
复制相似问题