Ruby on rails 如何计算rails模型列

Ruby on rails 如何计算rails模型列,ruby-on-rails,ajax,real-time,calc,Ruby On Rails,Ajax,Real Time,Calc,我有模型文章 迁移文件: class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.string :name t.string :description t.string :body t.string :keyword t.integer :price t.integer :count_

我有模型文章

迁移文件:

class CreateArticles < ActiveRecord::Migration
  def change
    create_table :articles do |t|
      t.string :name
      t.string :description
      t.string :body
      t.string :keyword
      t.integer :price
      t.integer :count_text
      t.integer :total_price
      t.timestamps
    end
  end
end
classcreatearticles
我有
ArticlesController
和两种标准方法
new
create

我创建了
new.html.erb
文件并使用了表单助手。 但字段和计数文本总价需要自动生成(价格*计数文本) Count_text-是正文行的大小。
用户在字段主体中输入文本,计算文本,然后乘以价格,并在确认创建记录之前显示给用户。如何制作?

您可能希望对这两列使用虚拟属性。如果你有兴趣,请查收


我自己也是个新手,但我相信其他人可以帮助您构建函数。虚拟属性似乎就是您要寻找的

据我所知,您希望在创建文章记录之前显示总价(count_text*price)。在rails端计算总价将包括不必要的服务器调用,因为用户可能会在看到文章价格时取消文章。使用javascript/jquery可以很容易地解决您的问题,您可以编写一个小函数来计算并显示总金额。 让我们假设a把数量写在标签上。 我想,您可以通过下面的代码了解一些情况:

<html>
<head>
<title> Demo Article </title>
<script src="jquery-1.5.1.min.js" type="text/javascript" ></script>
<script type="text/javascript">
$(document).ready(function() {
$("#txtBody").focusout(
function()
{
var count, total_price;
count = $("#txtBody").val().length; // get length of the text in the textarea
total_price = count * $("#price").val(); // multiple with the price per character
$("#txtBody").after('<br><mark> Total Price : ' + total_price +"</mark>"); // display the total price
}
)
$("#txtBody").focus(
function()
{
$("mark").remove(); // removes the total price if the body id currently edited
}
)
});
</script>
<style>
mark {font-size:1.875em;color:white;background-color:#DC143C;}
</style>
<head>
<body>
Price: <input type="text" readonly="true" id="price" value="7")><br>
Body : <textarea cols="30" id="txtBody"> </textarea>

</body>
</html>

演示文章
$(文档).ready(函数(){
$(“#txtBody”).focusout(
函数()
{
var计数,总价格;
count=$(“#txtBody”).val().length;//获取文本区域中文本的长度
total_price=count*$(“#price”).val();//每个字符的价格的倍数
$(“#txtBody”)。在(“
总价:”+总价+”)之后;//显示总价 } ) $(“#txtBody”).focus( 函数() { $(“标记”).remove();//如果主体id当前已编辑,则删除总价 } ) }); 标记{字体大小:1.875em;颜色:白色;背景色:#DC143C;} 价格:
正文:
您的问题很难理解,尤其是“但是…”之后的部分。有(至少)两个方面:在客户端动态计算(rails不会完成),在控制器中计算(但只有在提交后才可能)。你能澄清一下你想要什么吗?是的,我想知道如何做到这两个方面