验证失败后如何检索参数?

时间:2019-06-08 19:38:31

标签: ruby-on-rails ruby

验证失败后,我从link_to丢失了user_id参数,导致方法中出现以下错误:

undefined method `bank_account' for nil:NilClass

我的模特:

#user.rb
has_one :bank_account, inverse_of: :user, dependent: :destroy

#bank_account.rb
belongs_to :user, inverse_of: :bank_account
has_many :incoming_transfers, foreign_key: "target_bank_id", class_name: "AccountTransaction"
has_many :made_transfers, foreign_key: "source_bank_id", class_name: "AccountTransaction"

# account_transaction.rb
belongs_to :target_bank_account, foreign_key: "target_bank_id", class_name: "BankAccount"
belongs_to :source_bank_account, foreign_key: "source_bank_id", class_name: "BankAccount"

我的link_to和表单输入:

#link_to
<%= link_to ("Transfer credits to "+@user.name), new_account_transaction_path(user_id: params[:id]) %>

#form input
<%= f.input :target_bank_id, as: :hidden, input_html: { value: @user.bank_account.id } %>

我的控制器:

  #account_transactions_controller.rb
  def new
    @user = User.friendly.find(params[:user_id])
    @account_transaction = AccountTransaction.new
  end

  def create
    @account_transaction = AccountTransaction.new(account_transaction_params)

    if @account_transaction.save
      redirect_to @account_transaction, notice: "Transfer Completed."
    else
      render :new
    end
  end

日志:

NoMethodError - undefined method `bank_account' for nil:NilClass:
  app/views/account_transactions/_form.html.erb:7:in `block in _app_views_account_transactions__form_html_erb___1756003144041352821_70262592920360'
  app/views/account_transactions/_form.html.erb:1:in `_app_views_account_transactions__form_html_erb___1756003144041352821_70262592920360'
  app/views/account_transactions/new.html.erb:3:in `_app_views_account_transactions_new_html_erb__1529716313223870974_70262647907340'
  app/controllers/account_transactions_controller.rb:33:in `create'

1 个答案:

答案 0 :(得分:1)

我会将您的表格更改为此:

<%= simple_form_for @account_transaction do |f| %>
  ....

  <%= hidden_field_tag :user_id, @user.id %>

  <div class='form-inputs'>
    <%= f.input :amount %>
  </div>

  ....
<% end %>

请注意,您不会公开银行帐户ID,这更安全。您将user_id作为参数,这样就可以获取它的帐户,而current_user可以获取他的帐户。

现在执行创建操作

def create
  @user = User.find(params[:user_id])
  @account_transaction = AccountTransaction.new(
    source_bank_account: current_user.bank_account,
    target_bank_account: @user.bank_account,
    amount: params[:account_transaction][:amount]
  )

  if @account_transaction.save
    redirect_to @account_transaction, notice: "Transfer Completed."
  else
    render :new
  end
end

如果验证失败,则您已经具有@user变量来填写表格。