我有以下模型类:
class Movie < ActiveRecord::Base
has_and_belongs_to_many :actors
accepts_nested_attributes_for :actors, :allow_destroy => true
...
end
和
class Actor < ActiveRecord::Base
has_and_belongs_to_many :movies
...
end
movies/_form.html.haml 视图包含演员的嵌套表单:
...
= form_for @movie do |movie_form|
= movie_form.fields_for :actors do |actor_form|
= actor_form.text_field :id, "Id"
= link_to_remove_fields "remove", actor_form
= link_to_add_fields movie_form :actors
...
= movie_form.submit 'Save'
link_to_remove_fields
并且link_to_add_fields
是执行 javascript 调用、为新参与者添加新字段或删除参与者的辅助方法。
控制器:
class MovieController < ApplicationController
#POST form
def create
@movie = Movie.new(params[:movie])
...
end
#GET nearly empty form with one field for actor
def new
@movie = Movie.new
1.times {@movie.actors.build}
respond_to do |format|
format.html
format.json { render json: @movie }
end
end
end
问题:当按下“保存”(例如,只有一个 id=718 的参与者)并提交表单@movie = Movie.new(params[:movie])
时,控制器的行会抛出以下错误:
无法为 ID= 的电影找到 ID=718 的演员
我确定 Actor 数据库中有 id=718 的实体。