Reputation: 5
I have a mistake: couldn't find Subject without an ID in @subject = Subject.find(params[:subject_id])
I create many-to-many association. There are three models - teacher, subject and subscription. Subscription model includes following fields: teacher_id and 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
Upvotes: 0
Views: 681
Reputation: 5734
In the view, _form.html.erb, replace the select_tag
<%= select_tag "subject_id", options_from_collection_for_select(@subjects, "id", "name") %>
And in the controller code,
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
Upvotes: 0
Reputation: 17834
Do this instead
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
Upvotes: 1