Ruby on rails create方法在rails表中添加2个值并指定给属性
我试图获取一行的上一个余额,并将其添加到变量中,然后将其添加到params输入值中,并将其分配给特定的列属性。如果我rake db:migrate,并且表为空,它会说acctbal为nil,然后爆炸。如何在当前用户第一次存款时将该属性设置为0,以便后续存款可以基于该属性进行构建。如下面的代码所示,当添加2个值时,第二个+会给我一个未定义的nil错误。我只想连接这两个值,如何实现这一点Ruby on rails create方法在rails表中添加2个值并指定给属性,ruby-on-rails,ruby,Ruby On Rails,Ruby,我试图获取一行的上一个余额,并将其添加到变量中,然后将其添加到params输入值中,并将其分配给特定的列属性。如果我rake db:migrate,并且表为空,它会说acctbal为nil,然后爆炸。如何在当前用户第一次存款时将该属性设置为0,以便后续存款可以基于该属性进行构建。如下面的代码所示,当添加2个值时,第二个+会给我一个未定义的nil错误。我只想连接这两个值,如何实现这一点 def create #@account = Account.new(account_params) # @
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 %>
我想在账户模型中添加一个以前的余额方法:
请注意,只返回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
))
我懂了,当我这样做时,我仍然有+错误,我可以在模型中创建另一个方法,该方法将接受2个参数并将它们相加,然后返回结果,这样我就可以将其分配到控制器中吗?如果我实现此方法,它会错误地说:没有将Fixnum隐式转换为数组,并且具有acctbal:line highlighted参数[:存款]是从输入浮点值的创建页面提取的数据,我发布了我的_form.html.erb文件。它应该是信用卡吗?我在controllerits中发布了params方法,现在说,没有浮点到数组的隐式转换
# models/account.rb
def self.previous_balance_for_user(user)
where(user_id: user.id).order(:created_at).pluck(:acctbal).first || 0.0
end
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
))