I'm using namespaced models to assign different types of services to a platform :
Relation : Platform has_many :services
& Service belongs_to :platform
Inhéritance : Service::Service1 < Service
, Service::Service2 < Service
, etc.
Each service type has a different set of fields (I'm using Mongoid so fields are declared into the model and "submodel" type is stored in a _type
field).
In ServicesController::new
, I instanciate new services like this :
def new
klass = "service/#{params[:type]}"
@service = klass.camelize.constantize.new
render :form
end
params[:type]
is given by a route parameter (something like /:platform_id/services/new/:type
)
In my form
view, I can now display fields depending on the service type (it's Haml + simple_form) :
= simple_form_for @service do |f|
[...]
- case @service.class
- when Service::Service1
= f.input :field1
[...]
Everything works fine until now : Generated HTML inputs looks like this :
<input class="string required" id="service_service1_field1" name="service_service1[field1]" size="50" type="text">
With service_service1[field1]
as field name, my params hash will contain different keys depending on the sub-service and, in my controller's create
action, I'll have to write a case/when for each sub-service, while service[field1]
would have "DRYed" my code (I'd just have to add a hidden field with the exact model to instantiate).
Is there a way to force Rails to use the root class as field name when using namespaced models ?
Edit : Same question for submit button i18n : Rails looks for helpers.submit.service_service1.create
where I'd like it to look for helpers.submit.service.create
as the text is the same for all services.
simple_form_for :service
seems to work. I' thought it wasn't possible since rootService
class has noService1
field. I have to make more tests to validate there's no side effect (will the form get fields values on validation errors ?, etc...) – Gauthier Delacroixsubmit
instead ofcreate
orupdate
, validation errors does not feed fields with submitted values, etc. Finally not a solution. – Gauthier Delacroix