首先,我想简单地在我发送给back-end
的当前对象中获取一个对象。
我有这个简单的JSON
(从表单生成):
{
"name": "Project 1",
"project_criteria": [
{
"name": "Criterium 1",
"type": "Type 1",
"benefit": "1"
},
{
"name": "Criterium 2",
"type": "Type 2",
"benefit": "3"
}
]
}
我的classes
:
class Project < ApplicationRecord
has_many :project_criteria
accepts_nested_attributes_for :project_criteria
end
class ProjectCriterium < ApplicationRecord
belongs_to :project
end
ProjectsController:
def project_params
params.require(:project).permit(:name, project_criteria: [] )
end
但我仍然无法访问project_criteria
参数,如下所示:
Started POST "/projects" for 127.0.0.1 at 2016-08-19 16:24:03 -0300
Processing by ProjectsController#create as HTML
Parameters: {"project"=>{"name"=>"Project 1", "project_criteria"=>{"0"=>{"benefit"=>"1", "name"=>"Criterium 1", "type"=>"Type 1"}, "1"=>{"benefit"=>"3", "name"=>"Criterium 2", "type"=>"Type 2"}}}}
Unpermitted parameter: project_criteria # <-----------
注意:
顺便说一下,我已经尝试使用标准而不是标准( - 在我看来 - 是正确的,因为它应该<{1}}和has_many
中的复数形式,但它也不起作用。
有人有解决方案吗?
答案 0 :(得分:26)
这不是“标准”这个词给你带来问题的变化(虽然你可以添加一个自定义变形器来获得你喜欢的单数和复数版本)。
问题是您必须明确允许嵌套对象的字段。
更改您当前的参数:
params.require(:project).permit(:name, project_criteria: [] )
对此(对于单个嵌套对象):
params.require(:project).permit(:name, project_criteria: [:name, :type, :benefit] )
您处理多个嵌套对象的事实使您的情况更加复杂,因此您必须改为传递哈希:
params.require(:project).permit(:name, { project_criteria: [:name, :type, :benefit]} )
答案 1 :(得分:1)
在Rails 6应用程序上工作时遇到了这个问题。
我的应用程序包含一个User
模型,该模型与Personal_Info
模型具有一对一的关系
我的原始代码是这样的:
用户模型
class User < ApplicationRecord
has_one :personal_info, class_name: 'PersonalInfo', dependent: :destroy
accepts_nested_attributes_for :personal_info, allow_destroy: true
end
个人信息模型
class PersonalInfo < ApplicationRecord
belongs_to :user
end
用户控制器
class UsersController < ApplicationController
def index
@users = User.all
end
.
.
def user_params
params.require(:user).permit(:email, :password, :password_confirmation,
personal_info_attributes: [:first_name,
:last_name, :phone, :gender, :dob,
:address, :city, :state, :country])
end
end
问题是我没有将Personal_Info id添加到接受的用户参数(参数)中。
这是我修复的方式:
我只需要通过以下方式将Personal_Info id
添加到 UsersController 参数中:
用户控制器
class UsersController < ApplicationController
def index
@users = User.all
end
.
.
def user_params
params.require(:user).permit(:email, :password, :password_confirmation,
personal_info_attributes: [:id, :first_name,
:last_name, :phone, :gender, :dob,
:address, :city, :state, :country])
end
end
另一种方法是通过以下方式将update_only
选项添加到用户模型:
class User < ApplicationRecord
has_one :personal_info, class_name: 'PersonalInfo', dependent: :destroy
accepts_nested_attributes_for :personal_info, update_only: true, allow_destroy: true
end
仅此而已。
我希望这会有所帮助