create method添加2个值并分配给rails表中的属性

时间:2015-04-25 22:36:55

标签: ruby-on-rails ruby

我正在尝试获取行的前一个余额并将其添加到变量,然后将其添加到params输入值并将其分配给特定的列属性。如果我耙db:migrate并且表是空的,它会说acctbal是nil并且炸掉了。如何在current_user首次存入资金时将该属性设置为0,以便后续存款可以构建它。如下面的代码所示,第二个" +"当添加2个值给我一个未定义的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

1 个答案:

答案 0 :(得分:0)

我会在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
))