繁体   English   中英

创建方法添加2个值并分配给rails表中的属性

[英]create method adding 2 values and assigning to to an attribute in rails table

我试图获取行的先前余额并将其添加到变量中,然后将其添加到params输入值中并将其分配给特定的列属性。 如果我耙db:migrate并且表为空,它将说acctbal为零,然后炸开。 我如何仅当current_user首次存入资金时才将该属性设为0,以使后续的存款可以从中建立。 如下面的代码所示,将两个值相加时,第二个“ +”给我一个未定义的nil错误,我只想将两个值连接在一起,如何实现呢?

def create
 #@account = Account.new(account_params)
 # @account.save
 # respond_with(@account)

  @previous_balance = Account.where('user_id = ?', 
    current_user.id).order(:created_at).last.acctbal
  @account = Account.new(account_params)
  @account.email = current_user.email
  @account.user_id = current_user.id
  @account.acctbal = account_params[:deposit] + @previous_balance
  respond_to do |format|
     if @account.save
       format.html { redirect_to accounts_url, notice: 'Thank you and 
        enjoy.' }
       format.json { render :show, status: :created, location: @account }
  else
    format.html { render :new }
    format.json { render json: @account.errors, status: 
    :unprocessable_entity }
        end
      end
   end

我的表单不完整:

<%= form_for(@account) do |f| %>
 <% if @account.errors.any? %>
 <div id="error_explanation">
  <h2><%= pluralize(@account.errors.count, "error") %> prohibited this 
  account from being saved:</h2>

  <ul>
  <% @account.errors.full_messages.each do |message| %>
    <li><%= message %></li>
  <% end %>
   </ul>
   </div>
   <% end %>




<div class="field">
<%= f.label :credit, "Deposit Amount" %><br>
<%= f.text_field :credit, size: 40 %>
</div>
<div class="field">
<%= f.label :depotype, "Select Deposit Method" %><br>
<%= f.select :depotype, Account::DEPOSIT_TYPES, prompt: 'Select a deposit 
 method' %>
</div>
<div class="actions">
<%= f.submit 'Deposit Funds' %>
</div>
<% end %>

控制器中的params方法:

  def account_params
   # params[:account]
  params.require(:account).permit(:created_at, :email, :credit, :debit, 
  :acctbal, :depotype)
   end
   end

我将一个previous_balance方法添加到Account模型:

# models/account.rb
def self.previous_balance_for_user(user)
  where(user_id: user.id).order(:created_at).pluck(:acctbal).first || 0.0
end

需要注意的是pluck刚刚返回的值acctbal (或nil )。

使用该方法,您的控制器可以更改为:

previous_balance = Account.previous_balance_for_user(current_user)
@account = Account.new(account_params.merge(
  user_id: current_user.id,
  email: current_user.email,
  acctbal: previous_balance + account_params[:credit].to_f
))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM