为什么我会收到此 unpermitted params 错误?

Why am I getting this unpermitted params error?

我有一个 PortStock 模型,如下所示:

class PortStock < ApplicationRecord
  has_many :closed_positions, dependent: :destroy
  accepts_nested_attributes_for :closed_positions, allow_destroy: true
end

我的 ClosedPosition 模型是这样的:

class ClosedPosition < ApplicationRecord
  belongs_to :closer, class_name: "PortStock", foreign_key: "closer_id"
  belongs_to :closed, class_name: "PortStock", foreign_key: "port_stock_id" 
end

在我的 PortStockController 中,我的参数如下所示:

def port_stock_params
  params.require(:port_stock).permit(:portfolio_id, :stock_id, :closed_position, closed_positions_attributes: [:num_units, :closer_id, :port_stock_id, :closed_price, :_destroy])
end

这是表格:

<%= simple_form_for @port_stock, url: port_stocks_sell_order_path, method: :post, html: { class: "form-inline" } do |f| %>

  <% @buy_port_stocks.each do |port_stock| %>
    <%= f.simple_fields_for @cp, html: { class: "form-inline" } do |c| %>
      <div class="form-group">
        <%= c.input_field :port_stock_id, as: :hidden, value: port_stock.id %>
        <%= c.input_field :num_units, id: "sell-ps-#{port_stock.id}", placeholder: "Number of Units", class: "form-control mx-sm-3" %>
         <%= c.input_field :closed_price, id: "sale-price-for-ps-#{port_stock.id}", placeholder: "Sale Price", class: "form-control mx-sm-3" %>
       </div>
   <% end %>
  <% end %>
<% end %>

这是我的 PortStock#Create 操作:

@port_stock = current_user.port_stocks.friendly.find(params[:id])
@stock = @port_stock.stock
@cp = @port_stock.closed_positions.build

这是我尝试执行 create:

时的错误
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"M/TCcc79QcfOvoIc3z/cIFn83sjA==", "port_stock"=>{"closed_position"=>{"port_stock_id"=>"10", "num_units"=>"25", "closed_price"=>"9"}}, "commit"=>"Sell Stock", "id"=>"CAC"}
  User Load (1.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  ORDER BY "users"."id" ASC LIMIT   [["id", 2], ["LIMIT", 1]]
  ↳ /.rvm/gems/ruby-2.5.1/gems/orm_adapter-0.5.0/lib/orm_adapter/adapters/active_record.rb:17
  PortStock Load (1.6ms)  SELECT  "port_stocks".* FROM "port_stocks" INNER JOIN "portfolios" ON "port_stocks"."portfolio_id" = "portfolios"."id" WHERE "portfolios"."user_id" =  AND "port_stocks"."ticker" =  LIMIT   [["user_id", 2], ["ticker", "CAC"], ["LIMIT", 1]]
  ↳ /.rvm/gems/ruby-2.5.1/gems/friendly_id-5.2.4/lib/friendly_id/finder_methods.rb:60
Unpermitted parameter: :closed_position

可能是什么原因造成的?

首先,

因为您接受 closed_positions_attributes 作为嵌套属性,因此无需在强参数中添加 closed_position。如果您仍想访问 PortStock 中的 closed_position 属性,则在模型中使用 attr_accessor

其次,像下面这样更改嵌套形式以获得所需的参数。

f.simple_fields_for :closed_positions, @cp, html: { class: "form-inline" } do |c|

希望它能解决问题![​​=15=]