If this code is used in multiple controllers then is it best to
extract
it as a helper method or is there a different preferred way of doing
that?
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
(@entity.client).
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
like this:
before_filter :load_entity
def new
@client = Client.new
end
def create
@client = Client.new(params[:client])
@client.entity = @entity
@client.save!
end
private
def load_entity
#since this is a has_one, we can load the entity in for the whole
controller
@entity = Entity.find(params[:entity_id])
end
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:
redirect_to(new_entity_client_path(@entity))
Hope this helps.