Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change input name of model

Using the ActiveAttr:

class Filter
  include ActiveAttr::Model
  attribute term
  # Overriding to_key, to_param, model_name, param_key etc doesn't help :(
end

class SpecialFilter < Filter
end

How do I override the ActiveModel to generate the (same) predefined input names for all subclasses?

= form_for SpecialFilter.new, url: 'xx' do |f|
  = f.text_field :term

So instead of <input name='special_filter[term]' /> I need to get <input name='filter[term]' />

NOTE: The scenario is way much more complicated (with simple_form and radios/checkboxes/dropdowns etc), so please do not suggest to change the name of the class or similar workarounds. I really do need to have the consistent name to be used by the form builder.

like image 618
Dmytrii Nagirniak Avatar asked Sep 07 '12 07:09

Dmytrii Nagirniak


2 Answers

Try this :

= form_for SpecialFilter.new, as: 'filter', url: 'xx' do |f|
  = f.text_field :term
like image 144
ddb Avatar answered Nov 14 '22 20:11

ddb


As Divya Bhargov answered, if you take a look at the source code you'll find out the internal call stack should end up like below.

 # actionpack/lib/action_view/helpers/form_helper.rb
 ActiveModel::Naming.param_key(SpecialFilter.new)

 # activemodel/lib/active_model/naming.rb 
 SpecialFilter.model_name

So, if you really want to do it in your model level, you need to override the model_name to your class.

class SpecialFilter < Filter
  def self.model_name
    ActiveModel::Name.new(self, nil, "Filter")
  end
end    

The parameter for this ActiveModel::Name initializer is klass, namespace = nil, name = nil.

But model_name is also used somewhere else such as error_messages_for, so do use this with care.

like image 36
kinopyo Avatar answered Nov 14 '22 22:11

kinopyo