【问题标题】:How to calc rails models columns如何计算rails模型列
【发布时间】:2012-01-07 09:53:35
【问题描述】:

我有模型文章。

迁移文件:

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 - 是正文线的大小。 用户在字段正文中输入文本,计算文本然后乘以价格并在确认创建记录之前显示给用户。如何制作?

【问题讨论】:

  • 您的问题很难理解,尤其是“But the ..”之后的部分。有(至少)两个方面:在客户端动态计算(不会由 rails 完成),在控制器中计算一些东西(但只有在提交后才有可能)。你能澄清一下你想要什么吗?
  • 是的,我想知道如何做到这一点

标签: ruby-on-rails ajax real-time calc


【解决方案1】:

据我理解的问题,您希望在创建文章记录之前显示 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>

【讨论】:

    【解决方案2】:

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

    我自己是新手,但我相信其他人可以帮助您构建这些功能。虚拟属性似乎是您正在寻找的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-26
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-18
      • 2017-08-21
      • 1970-01-01
      相关资源
      最近更新 更多