Rails - changing default param_key for a model
Asked Answered
U

1

6

I've been using plain Ruby form objects in rails, but to keep my code organized, I've ended up having to add a ton of namespaces to them. So I'll have a form like:

class User::Registration::NewForm
  extend Forwardable
  extend ActiveModel::Naming
  extend ActiveModel::Callbacks
  include ActiveModel::Conversion
  include ActiveModel::Validations

  ...
end

The annoyance with this is that the param_key for my forms becomes kind of daunting, e.g. user_registration_new_form

I'd like to override this somehow, and I think I need to mess with the model_name and/or param_key methods from ActiveModel::Naming (http://apidock.com/rails/ActiveModel/Naming/param_key/class). But I can't get it to work.

Has anyone been able to successfully override the default param_key for a model?

Unblinking answered 31/10, 2013 at 1:22 Comment(0)
U
6

Gah, I finally got it! You just need to define a class model_name method, and return an ActiveModel::Name object.

So something like:

self.model_name
  ActiveModel::Name.new(User)
end
Unblinking answered 31/10, 2013 at 14:55 Comment(2)
I had to do ::ActiveModel::Name.new(User) otherwise uninitialized constant Reform::Form::ActiveModel::Name.Nadianadine
You can also do something like: def model_name; Struct.new(:param_key, :name).new('form', 'form'); end.Wongawonga

© 2022 - 2024 — McMap. All rights reserved.