0
votes

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.

1
simple_form_for :service seems to work. I' thought it wasn't possible since root Service class has no Service1 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 Delacroix
First side effect: By using a symbol instead of an object, the form builder does not know if it's a create or update action : ID hidden field is not added on edit, I18n looks for submit instead of create or update, validation errors does not feed fields with submitted values, etc. Finally not a solution.Gauthier Delacroix

1 Answers

1
votes

Have you tried the :as option? I have used this for sub classes but not for name spaces. You may have to do some additional gymnastics with the :url option to get your form to post to the correct location.

If you have an object that needs to be represented as a different parameter, 
like a Person that acts as a Client:

<%= form_for(@person, :as => :client) do |f| %>
  ...
<% end %>

Taken from the Rails docs