If this code is used in multiple controllers then is it best to
it as a helper method or is there a different preferred way of doing
Helpers are really meant to help automate view components. If you want
to share some common functionality to your controllers, I would put that
code into a module, and save it in the “lib” folder. You can then
include that in your controllers (or models, or views) by just adding
“include MyModule” to the controllers you want it accessible to. If you
think it should be accessible to all your controllers, you can add the
include statement to your ApplicationController.
I would say only use a module if it’s really necessary to share code.
Typically, you’ll want to keep your CRUD operations inside of the
controller. You’re right that models shouldn’t invoke the controller,
but I think you’re forgetting that the Entity model and the Client model
are already connected through their relationship.
In your Client Controller, you should have no trouble accessing it’s
Entity through @client.entity, and vice versa in the Entity Controller
So from the previous example, if you go to edit an Entity with no
client, it redirects to the Client’s new action, where you ask a user if
he’d like to add a client. Your client controller might look something
@client = Client.new
@client = Client.new(params[:client])
@client.entity = @entity
#since this is a has_one, we can load the entity in for the whole
@entity = Entity.find(params[:entity_id])
You’ll have to be passing the :entity_id in from somewhere. You can do
this in your re-directs:
redirect_to(new_client_path, :entity_id => @entity.id)
or if you’re using nested routes:
Hope this helps.