gpt4 book ai didi

ruby-on-rails - rails : submit form with nested attributes throws 'couldn' t find entity with id=xxx'

转载 作者:行者123 更新时间:2023-12-04 04:57:52 25 4
gpt4 key购买 nike

我得到了以下模型类:

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

movie/_form.html.haml View 包含 Actor 的嵌套表单:
...
= 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_fieldslink_to_add_fields是执行 javascript 调用、为新角色添加新字段或删除角色的辅助方法。

Controller :
   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 的 Actor )并提交表单时, @movie = Movie.new(params[:movie]) Controller 的行引发以下错误:

Couldn't find Actor with ID=718 for Movie with ID=



我确定 Actor 数据库中有 id=718 的实体。

最佳答案

如果您尝试将现有 Actor 与新电影相关联,最简单的方法就是不要使用 accepts_nested_attributes根本。

您从 Actor 协会获得的一件事是 actor_ids ,它返回关联 Actor 的 id,或者允许您设置关联 Actor 的列表。

要通过 rails 表单提交数组,输入的名称必须以 [] 结尾,例如,如果您的输入名称为 movie[actor_ids][]并取值 1,然后你会得到

{'movie' => {'actor_ids' => ['1']}}

在您的 Controller 中。如果您想提交第二个参与者,只需创建另一个具有相同名称的输入 movie[actor_ids][] .您也可以使用带有 multiple 的选择框属性集,但它们对用户来说可能有点不友好,尤其是当有多个选项可供选择时。

关于ruby-on-rails - rails : submit form with nested attributes throws 'couldn' t find entity with id=xxx',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16538948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com