在Rails 4中提交表单后引用和操作params - ActiveModel :: ForbiddenAttributesError

时间:2014-03-21 02:38:38

标签: ruby-on-rails ruby-on-rails-4

在Rails 4中,我们必须更改为强参数。我还没想出如何引用特定的参数。我一直遇到这个错误:

ActiveModel::ForbiddenAttributesError in TransactionsController#create

创建事务时,我想在创建新对象之前操作一些参数。我还想保存Account的ID(在表单中以hidden_field_tag形式发送)。

这是我的表格:

#newTransaction-modal.modal.hide.fade style="display: none;"
  h3 New Transaction
  = form_for Transaction.new do |f|
    p Date:
    = f.text_field :transaction_date, value: Time.now.strftime("%m/%d/%Y") 
    p Payee: 
    = f.text_field :payee
    p Category: 
    = f.select :category, options_for_select(["Phone", "Restaurants", "Gas/Fuel"])
    p Memo: 
    = f.text_field :memo
    p Outflow: 
    = f.text_field :outflow, value: 0
    p Inflow:
    = f.text_field :inflow, value: 0
    = hidden_field_tag :account_id, value: params[:id]
    br
    a.btn href="#"  data-dismiss="modal" Cancel

    = f.submit "Create Transaction", class: "btn"

和我的交易控制器:

class TransactionsController < ApplicationController
  load_and_authorize_resource

  def create
    transaction_date = Date::strptime(transaction_params, "%m/%d/%Y")
    outflow = params[:transaction][:outflow].include?(".") ? params[:transaction][:outflow].gsub(".", "").to_i : (params[:transaction][:outflow] + "00").to_i
    inflow = params[:transaction][:inflow].include?(".") ? params[:transaction][:inflow].gsub(".", "").to_i : (params[:transaction][:inflow] + "00").to_i

    @account = Account.find(params[:account][:id])
    @transaction = @transaction.new(transaction_params)

    @transaction.user_id = current_user.id    
    @transaction.account_id = @account.id
    @transaction.transaction_date = transaction_date
    @transaction.outflow = outflow
    @transaction.inflow = inflow
    @transaction.save


    diff = inflow - outflow
    new_account_balance = @account.balance + diff
    @account.update_attributes(balance: new_account_balance)
    redirect_to account_path(@account)
  end

  private
  def transaction_params
    params.require(:transaction).permit(:transaction_date, :payee, :account_id, :category, :memo, :inflow, :outflow, :user_id)
  end

end

如何在控制器中引用account_id?

1 个答案:

答案 0 :(得分:0)

我也允许帐户的参数。您可以将{account_attributes:{:id}}添加到transaction_params方法,这将允许它。然后你可以调用transaction_params并获取你可以随意修改的params的哈希值。