gpt4 book ai didi

ruby-on-rails - accepts_nested_attributes_for 上不允许的参数

转载 作者:数据小太阳 更新时间:2023-10-29 08:27:31 25 4
gpt4 key购买 nike

所以我对 Rails 还很陌生,所以我可能遗漏了一些非常直接的东西..

我想做的是在创建 Band 时创建一个 Artist

模型

乐队.rb

class Band < ActiveRecord::Base

has_many :artists, dependent: :destroy

accepts_nested_attributes_for :artists, allow_destroy: true

...

end

艺术家.rb

class Artist < ActiveRecord::Base

belongs_to :band

...

end

Controller 带 Controller .rb

class BandController < ApplicationController

def new
@band = Band.new
end

def create

@band = Band.new(band_params)
if @band.save
...
else
...
end

end

private

def band_params
params.require(:band).permit(:name, :hometown, :email, :artist, artist_attributes: [ :band_id, :first_name, :last_name, :email, :password, :password_confirmation ])
end

end

查看

new.html.erb

<%= form_for(@band, url: "/artist/signup") do |f| %>

<%= render 'shared/error_messages', object: f.object %>

<%= f.fields_for :artist do |artist| %>
<%= artist.text_field :first_name, :placeholder => "First Name", :maxlength => 100 %>
<%= artist.text_field :last_name, :placeholder => "Last Name", :maxlength => 100 %>

<%= artist.email_field :email, :placeholder => "Email Address", :maxlength => 255 %>
<%= artist.password_field :password, :placeholder => "Password", :maxlength => 255 %>
<%= artist.password_field :password_confirmation, :placeholder => "Confirm Password", :maxlength => 255 %>
<% end %>

<%= f.text_field :name, :placeholder => "Band Name", :maxlength => 100 %>
<%= f.text_field :hometown, :placeholder => "Hometown", :maxlength => 100 %>
<%= f.text_field :email, :placeholder => "Band Email", :maxlength => 100 %>
<%= f.submit "Apply", class: "button" %>

<% end %>

我的开发日志是这样写的:

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "band"=>{"artist"=>{"first_name"=>"", "last_name"=>"", "email"=>"", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "name"=>"", "hometown"=>"", "email"=>""}, "commit"=>"Apply"}
-----
Unpermitted parameters: artist
{"name"=>"", "hometown"=>"", "email"=>""}
-----

现在,我认为我不需要允许艺术家,因为它是一个散列。即使我允许它,它也不会改变。有什么想法吗?

最佳答案

好的,在#RubyOnRails 的帮助下我已经弄明白了。

我需要在 BandController 的新 Action 中构建艺术家

@band.artists.build

然后通过 form_for(@band) 进入 View ,.fields_for :artist 更改为 .fields_for :artists , 和

  params.require(:band).permit(:name, :artist, artist_attributes: [ :band_id, :first_name ])

改变为

  params.require(:band).permit(:name, artists_attributes: [ :band_id, :first_name ])

关于ruby-on-rails - accepts_nested_attributes_for 上不允许的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20470412/

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