在控制器中的一个创建操作上插入两行
我有一个用于记录交易的表格。液体从一个罐转移到另一个罐。我的表格获取了来自罐和目的地罐以及转移的加仑数。我希望将其作为两行输入数据库。第一行是来源罐 ID 和负数,第二行是目的地罐 ID 和正数。
例子: 将 36 加仑从 Tank 1 转移到 Tank 2
id | tank_id | tran_amount
------------------------------
1 | 1 | -36
2 | 2 | 36
这是我可以轻松地用 PHP 编写 SQL 代码来实现的目标,但我对 Rails 感到不知所措。我怎样才能从一种形式做到这一点?
I have a form that is used to record a transaction. Liquid is moved from one tank to another. My form takes the from tank and the to tank and the number of gallons transferred. i would like this to be entered into the database as two rows. The first would be the from Tank ID and a negative number and the second row would be the to Tank ID and a positive number.
Example:
Transferring 36 gallons from Tank 1 to Tank 2
id | tank_id | tran_amount
------------------------------
1 | 1 | -36
2 | 2 | 36
This is something that I would have achieved with ease writing SQL code in PHP but I am at a loss in Rails. How can I do this from one form?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的数据库模型中似乎缺少一些东西,您不想要一些东西将传输绑定在一起吗?我会这样做:
如果您坚持使用现有模型(假设位于名为 Transfer 的模型中),则没有什么可以阻止您在控制器中创建两个模型,只需将它们放入事务中即可。
Something seems missing in your database model here, don't you want something to tie the transfer together? I would do:
If you are stuck with the existing model, which assume is in a model called Transfer, there is nothing that prevents you from creating two in the controller, just put them in a transaction.
他的模型是正确的。会计式交易表只保存账户ID和交易金额。您必须使用事务保存来确保两条记录都正确保存,否则两条记录都会失败。
为此,我会选择简单的表单标签版本。
然后,在控制器中,我创建两个传输模型并将它们一起保存为事务。
His model is correct. An accounting-style transaction table only holds the account ID and the transaction amount. You must use a transaction save to ensure that both records save correctly or both records fail.
For this, I'd go for just the easy form tag version.
In the controller, I'd then create both transfer models and save them together as a transaction.
我会以不同的方式对此进行建模。希望这能给您一些想法...我不确定它是否会按原样工作...
然后您的表单看起来像(如果您使用的是 formattastic):
您的控制器将是一个非常简单的控制器,就像您在所有示例中看到的那样。
I would model this differently. Hopefully this gives you some ideas... I'm not sure if it'll work as is...
Then you're form would look like (if you were using formtastic):
You're controller would be a very simple controller, just like you see in all the examples.