2011-11-27 70 views
2

我有模型文章。如何计算导轨模型列

迁移文件:

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 

我有ArticlesController两个标准方法newcreate

我做new.html.erb文件和使用的形式助手。 但字段和count_text total_price需要自动生成(price * count_text) Count_text - 是正文行的大小。 用户在字段正文中输入文本,计算文本,然后乘以价格并在确认创建记录之前将其显示给用户。如何做到这一点?

+0

你的问题很难理解,特别是在部分“但是......”。至少有两个方面:在客户端动态计算(不会由rails完成),在控制器中计算某些内容(但只能在提交后才能完成)。你能澄清你想要的吗? – mliebelt

+0

是的,我想知道这怎么可以做到这两种方式 – user988158

回答

0

就我所了解的问题而言,您希望在创建文章记录之前显示total_price(count_text * price)。计算rails侧的总价格将包含不必要的服务器调用,因为用户可能会取消该文章看到文章的价格。您可以使用javascript/jquery轻松解决问题,您可以在其中编写一个小函数来计算以显示总金额。 可以说一个标签上的金额。 你可以得到一些想法与此代码下面我猜:

<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> 
+0

非常感谢,需要添加total_price到表的字段。 – user988158

2

您可能想要为这两列使用虚拟属性。如果你有兴趣检查here

我自己是新手,但我确信其他人可以帮助您构建函数。虚拟属性似乎是你正在寻找的。

+0

谢谢我会看,非常感谢 – user988158