How to use nested attributes with belongs_to association on new action?

廉价感情. 提交于 2019-12-24 17:55:00

问题


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 .



来源:https://stackoverflow.com/questions/13431465/how-to-use-nested-attributes-with-belongs-to-association-on-new-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!