我正在学习Ruby on Rails的表单助手和阅读https://guides.rubyonrails.org/form_helpers.html文档我正在尝试在计算机上进行练习,但它根本无法按照文档中所描述的那样工作,我得到的只是
Started POST "/players" for ::1 at 2023-09-15 22:48:45 -0600
Processing by PlayersController#create as TURBO_STREAM
Parameters: {"authenticity_token"=>"[FILTERED]", "player"=>{"name"=>"Luis", "number"=>"45", "jersey"=>{"size"=>"M"}}, "commit"=>"Create Player"}
Unpermitted parameter: :jersey. Context: { controller: PlayersController, action: create, request: #<ActionDispatch::Request:0x00007f117a4a0640>, params: {"authenticity_token"=>" [FILTERED]", "player"=>{"name"=>"Luis", "number"=>"45", "jersey"=>{"size"=>"M"}}, "commit"=>"Create Player", "controller"=>"players", "action"=>"create"} }
和泽西岛的关系并没有持续下去。我在Acer硝基AN 515 -55上的Ubuntu 22.04.3 LTS上使用Rails 7.0.8和Ruby 3.2.1
这是一个简单的例子。模型是:玩家拥有_多件球衣
class Player < ApplicationRecord
has_many :jerseys, dependent: :destroy
accepts_nested_attributes_for :jerseys
end
class Jersey < ApplicationRecord
belongs_to :player
end
players_controller(仅index、new、create和player_params)
# GET /players or /players.json
def index
@players = Player.all
@player = Player.new
end
# GET /players/new
def new
@player = Player.new
end
# POST /players or /players.json
def create
@player = Player.new(player_params)
respond_to do |format|
if @player.save
format.html { redirect_to players_url, notice: "Player was successfully created." }
format.json { render :show, status: :created, location: @player }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @player.errors, status: :unprocessable_entity }
end
end
end
# Only allow a list of trusted parameters through.
def player_params
params.require(:player).permit(:name, :number, jerseys_attributes: [:id, :size])
end
我在index.htl.erb中有表格
<%= form_with(model: @player) do |form| %>
<div>
<%= form.label :name, style: "display: block" %>
<%= form.text_field :name %>
</div>
<div>
<%= form.label :number, style: "display: block" %>
<%= form.number_field :number %>
</div>
<div>
<%= form.fields_for :jersey do |jersey_form| %>
<%= jersey_form.label :size, style: "display: block" %>
<%= jersey_form.text_field :size %>
<% end %>
</div>
<div>
<%= form.submit %>
</div>
<% end %>
<div id="players">
<% @players.each do |player| %>
<%= render player %>
<p>
<%= link_to "Show this player", player %>
</p>
<% end %>
</div>
<%= link_to "New player", new_player_path %>
我也试过:
<%= form.fields_for :jersey, @player.jerseys do |jersey_form| %>
但结果是一样的...在这一点上,我不知道是什么错了,这是一个简单的例子,但我不能使它工作,请帮助我
1条答案
按热度按时间68bkxrlz1#
accepts_nested_attributes_for :jerseys
表示:通过这种方式,表单生成器可以检测
jerseys
关联并生成正确的jerseys_attributes
输入名称。更新
不如我们从头开始:
填写并提交:
索引操作的工作原理是一样的: