在 Rails 中的另一个模型视图中显示一个模型的逻辑?
我有一个模型“统计”,它有 6 个角色模型的统计数据。用户可以输入力量、智力等值。我编写了一种根据输入的分数自动计算奖金或处罚的方法。以下是我的统计模型中的体质奖励的逻辑:
def con_modifier
(constitution.to_i - 10) / 2
end
我在角色视图中显示从统计模型收集的信息,并且我想查看奖励,因此我在角色模型的 Show 方法中定义了它,如下所示:
@con_modifier = @character.statistic.con_modifier
我可以在角色视图中查看它,没有任何问题。但这是我的问题。我有另一个模型,Fortitude,它需要获取这个数字并用它来计算 Fortitude 保存的总价值。到目前为止,这就是我所得到的:
def total
fortitude_base.to_i + @con_modifier + magic.to_i + misc.to_i
end
但随后我收到此错误:
nil can't be coerced into Fixnum
显然它没有调用正确的信息。有什么想法吗?我是否也需要在 Fortitudes 控制器中定义它,或者我可以简单地在 Fortitude 模型中定义它并以这种方式在视图中调用它吗? Fortitude 正在我的角色视图中显示,所以我认为在角色模型的 Show 方法中定义这个逻辑会很简单,但是我已经为这个问题绞尽脑汁好几天了,但没有任何进展。谢谢!
I have a model, Statistic, that has 6 statistics for a Character model. Users can enter values for Strength, Intelligence and so on. I've written a method for automatically calculating bonuses or penalties based on the score entered. Here's the logic for a Constitution bonus, from my Statistic model:
def con_modifier
(constitution.to_i - 10) / 2
end
I display the information gathered from the Statistic model in my Character view, and I want to see the bonus, so I defined it in the Show method in my Character model like so:
@con_modifier = @character.statistic.con_modifier
I'm able to view it in the Character view with no issues. But here's my problem. I have another model, Fortitude, which will need to take this number and use it to calculate the total value for a Fortitude save. So far, here's what I've got:
def total
fortitude_base.to_i + @con_modifier + magic.to_i + misc.to_i
end
But then I get this error:
nil can't be coerced into Fixnum
So obviously it isn't calling up the correct information. Any ideas? Do I need to define it in my Fortitudes controller as well, or can I simply define it in the Fortitude model and call it in the view that way? The Fortitude is being displayed in my Character view, so I thought defining this logic in the Show method in the Character model would simply work, but I've been hammering my head against this problem for a couple days now, with no progress. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将修饰符作为参数传递:
然后在其他地方使用它:
Pass the modifier as an argument:
Then use it elsewhere: