Displaying logic from one model in the view of another in Rails?
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 pe开发者_运维知识库nalties 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!
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)
精彩评论