ruby - create method adding 2 values and assigning to to an attribute in rails table -
i trying previous balance of row , add variable add params input value , assign specific column attribute. if rake db:migrate , table empty acctbal nil , bomb out. how attribute 0 first time current_user has deposited funds, such following deposit can build off of it. seen in code below, second "+" when adding 2 values gives me undefined nil error want concatenate both values, how can achieve this?
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 |format| if @account.save format.html { redirect_to accounts_url, notice: 'thank , 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
my form partial:
<%= form_for(@account) |f| %> <% if @account.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@account.errors.count, "error") %> prohibited account being saved:</h2> <ul> <% @account.errors.full_messages.each |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 deposit method' %> </div> <div class="actions"> <%= f.submit 'deposit funds' %> </div> <% end %>
params method in controller:
def account_params # params[:account] params.require(:account).permit(:created_at, :email, :credit, :debit, :acctbal, :depotype) end end
i add previous_balance
method account
model:
# models/account.rb def self.previous_balance_for_user(user) where(user_id: user.id).order(:created_at).pluck(:acctbal).first || 0.0 end
note pluck
returns values of acctbal
(or nil
).
with method controller can changed to:
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 ))
Comments
Post a Comment