0

我有一个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" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["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" = $1 AND "port_stocks"."ticker" = $2 LIMIT $3  [["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

这可能是什么原因造成的?

4

1 回答 1

2

第一的,

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

其次,将嵌套形式更改为如下所示以获取所需的参数。

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

希望它能解决问题!

于 2018-06-27T07:22:55.513 回答