在提交到 RoR 之前,如何在模型方法中获取属性值?

How do I get the value of an attribute in a model method before submitting in RoR?

假设我有一个属性 :year_of_birth 和另一个字段 :age(只读),我填写 year_of_birth。我在模型中创建了一个方法来计算年龄,年龄如何填充到视图中?

这是我做的一个简短的代码片段,应该让您走上正确的道路(使用 javascript,但没有 rails 上的 ruby,如评论中所述)。

document.getElementById("date").value获取id为“date”的元素的值。您只需将日期(我假设它只是出生年份)减去 2020 年即可。

Date of birth: <input type="int" id="date">
Age: <input type="int" id="age">

<p>Click the button to get the age!</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById("age").value = 2020 - document.getElementById("date").value;
}
</script>

这只是一个基本脚本,几个月后不会可用,因为我们将在 2021 年提供,因此我将让您在 javascript 中找到如何获取当前年份。它也不是完全准确,因为它没有考虑 month/day 出生,但你明白了!

我希望这对你有所帮助,如果有什么不清楚或没有按照你想要的方式工作,请告诉我。

编辑:哦,我忘了说,但是这段代码是在您单击按钮后执行的,这可能不是真正的用户友好(取决于您在做什么,真的!)。如果您想让函数在填充字段后立即执行,则需要进行一些修改。

如果你想在出生年份改变时立即显示年龄,你可以像这样在输入中添加onchange事件:

Date of birth: <input type="int" id="date" onchange=myFunction()>
Age: <input type="int" id="age">

<p>Fill the first area with a year to get the age!</p>

<script>
function myFunction() {
  document.getElementById("age").value = 2020 - document.getElementById("date").value;
}
</script>

只要您按下回车键或在文本区域外单击,onchange 事件就会触发。