在 Rails 中的另一个模型视图中显示一个模型的逻辑?

发布于 2024-12-05 21:37:03 字数 778 浏览 3 评论 0原文

我有一个模型“统计”,它有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑着哭最痛 2024-12-12 21:37:04

将修饰符作为参数传递:

def total(con_mod)
  fortitude_base.to_i + con_mod + magic.to_i + misc.to_i
end

然后在其他地方使用它:

@fortitude = Fortitude.whatever
@saving_throw = @fortitude.total(@character.statistic.con_modifier)

Pass the modifier as an argument:

def total(con_mod)
  fortitude_base.to_i + con_mod + magic.to_i + misc.to_i
end

Then use it elsewhere:

@fortitude = Fortitude.whatever
@saving_throw = @fortitude.total(@character.statistic.con_modifier)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文