I have a model that gets treated differently by a parameter it holds, for example its like a character table, which also is used for non player characters, since they share all the same attributes. So it would have a Boolean or integer that would indicate if it was a player character or a non-player character. And non-player characters will be generated automatically with random status parameters and names.
Since the methods used for the two are radically different, I though it would be logical to have a different controller class for them, but that would make a single model have two different controllers, and feels somewhat odd.
Is this bad practice? Should I do all the coding in one controller?
Show activity on this post. If i am understanding you correctly, you can still use one controller, you just need different views. In your controller you can have your if type == regular then render commonpost.
You need a controller just when you have request actions on the relative model; When a model is just for data calculation and basic business logic implementation, don't generate the controller.
The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.
It actually sounds to me like you should have two different models. If the way you interact with the objects is radically different, as you explained, then they really shouldn't be the same class. Ruby has a great way to deal with this case: Modules. You can use modules to create shared behaviors for objects. You can even store the non-player characters and characters in the same database table by overriding the ActiveRecord table name. For example:
module Character
def decrease_hitpoints x
...
end
# other shared functionality can go here
end
class PlayerCharacter < ActiveRecord::Base
set_table_name 'characters'
include Character
end
class NonPlayerCharacter < ActiveRecord::Base
set_table_name 'characters'
include Character
end
In this example both PlayerCharacter and NonPlayerCharacter share the same table name and functionality defined in Character, but they are different objects.
Finally, it's totally fine to use two or more controllers for a single model, just as it's fine to build a controller that doesn't depend on a model at all.
This is completely OK. What you are describing is a task-based user interface, where you are more interested in capturing a work flow or process, as opposed to a simple CRUD or resource operation. Remember, the default setups in Rails are meant to be very basic. Feel free to expand on the basics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With