我希望用一个动作更新现有记录的列,但由于我不能这样做,现在有两个动作。
让用户指定要添加到现有列的数字 如果用户指定3,并且现有列为97,则总共100和数字,100将被保存。
查看Set<String> updatedFields = new HashSet<>(updates.keySet());
split_now.html.erb
这是验证器
<div class="container">
<h1>Split</h1>
<%= form_for @currency, url: { action: 'split', controller: 'currencies'}, method: :put do |f|%>
<% if @currency.errors.any? %>
<div id="error_explanation" class="alert alert-danger">
<h2><%= @currency.errors.count %>error(s) exist(s).</h2>
<ul>
<% @currency.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>amount whatever you want to issue like 100</p>
<div class="input-group">
<%= f.text_field :amount,:class=>'form-control form-group',placeholder:"amount"%>
</div>
<%= f.submit 'done', class: "btn btn-large bg-info" %>
<% end %>
</div>
def split_now
@currency=Currency.find_by_slug(params[:id])
end
def split
@currency=Currency.find_by_slug(params[:id])
if CurrencyUser.where(currency_id:@currency.id,owner:true).first.user==current_user
if SplitValidation.new(amount:params[:amount]).valid?
issue_more(params,@currency)
else
render "split_now"
end
else
redirect_to @currency,alert:"This currency wasn't issued by you"
end
end
def issue_more(params,currency)
result=false
current_amount=currency.amount
result=currency.update(
amount:current_amount+params[:amount].to_i
)
currency_user=CurrencyUser.find_by(currency_id:currency.id,owner:true)
currency_user.update(amount:currency_user.amount+params[:amount].to_i)
return result
end`
路由
class SplitValidation
include ActiveModel::Model
attr_accessor :amount
validates :amount, presence: true,numericality: { only_integer: true,greater_than: 0 }
end
答案 0 :(得分:1)
尝试以下内容,我想你想要这样:
currency_user.increment('amount', params[:amount].to_i)
或
currency_user.increment!('amount', params[:amount].to_i)
或
currency_user.update_attributes({'amount': currency_user.amount + params[:amount].to_i})
或
currency_user.update_attribute(amount: currency_user.amount + params[:amount].to_i)
<强>更新强>
以下方法跳过验证,并将对象保存到数据库,无论其有效性如何。应谨慎使用它们。 Skipping Validations
更新2
要进行验证,您可以使用HTML默认验证器<input type="number" min="1" name="number" step="1" required/>
,请参阅以下代码并附上alert
示例,只需按下即可运行,看看发生了什么。
$(document).on('submit', '#myForm', function(e){
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="//google.com">
<p>Input type number step any</p>
<input type="number" min="1" name="number" step="1" required/>
<input type="submit"/>
</form>
希望它能奏效。