Reputation: 48626
I know that generally speaking, including controller code in the views is not a good idea. However, are there any cases where that this is not entirely true ? For instance, what about this example :
<%= link_to "Upgrade (costs #{ Skill.get_profession_cost('Admin')} gold)" ...
In this example, i need to get the profession cost for more than one roles (Admin, User and more). Therefore, there are many links like the one above. Now the question is what is the best practise of doing that. I can think of 3 ways:
Just as shown above.
Use a helper and get the cost (disadvantage - i need the get_profession_cost function in a model anyway, since i use it in a controller; thus, a helper seems a bit redundant to me). Moreover, i kinda reckon a helper as code that should be in the controller anyway.
Get a prearranged hash like :
User => 1000, Admin => 3000 ... and more. This is more cumbersome though and kinda tedious to create.
I would really like your opinion. Is there any better way and if not, which one would you prefer ?
Upvotes: 2
Views: 113
Reputation: 6138
My order of preference is always
It's good you've got a method on your model. I'd say go one step further and add a class method on your model that gets the hash of all profession costs. The advantage to this is you can probably do a single DB query (that will be cached) rather than one for each profession. Keep your controllers as skinny as possible.
You can then get the hash in every place in the controller you need it (or use a filter to add it in lots of places).
I'd still add a helper that generates the string (not just the number)
(costs 12 gold)
if it is used several times.
Upvotes: 5
Reputation: 181
I would try and contain all computations within the controller.
An example of when to include Ruby code in the view could be:
- if boolean_2
% some_html
-if boolean_2
% other_html
(Haml syntax)
Boolean 1 and 2 would be set in the controller, the view would just be making use of the result.
Of course for small amounts of code like your example above it probably doesn't matter. Usually I'd keep as many method calls as possible in the controller and pass hashes between the view and controller.
Just my opinion.
Upvotes: 0