How to use nested attributes with belongs_to assoc

2019-07-27 00:09发布

问题:

On the update action the following nested_form works, but on create I get this error:

Couldn't find Student with ID=12 for Cv with ID=


Controller:

def new
  @cv = Cv.new
  @cv.student = current_student
end

def create
  @cv = Cv.new(params[:cv])

  if @cv.save
    redirect_to student_dashboard_path,
      notice: t('activerecord.successful.messages.created', model: @cv.class.model_name.human)
  else
    render 'new'
  end
end


Model:

class Cv < ActiveRecord::Base
  attr_accessible :student_attributes

  belongs_to :student
  accepts_nested_attributes_for :student
end


View:

= f.simple_fields_for :student do |s|
  = s.input :english_level, collection: [['Low', 1], ['High', 2]]

回答1:

You should make changes to your route.rb too.

resources :parent do
  resources :child
end

Take a look at this useful implementation by Jose Valim - inherited-resources .