Using Rails Form Helpers for Non-Existing Methods

Usually, when using form helpers in Rails, each field directly correlates with the method of the corresponding object.

However, I have a form (user registration) that should include fields that are not part of the user model itself (for example, map data), but should appear.

How can I create a form so that I can get the required fields and check them as I need (so that they match all my other validations) without polluting my user model?

+4
source share
2 answers

I'm not sure what you mean by a "dirty" user model, but you can do this using the attr_accessor method . This will allow you to create an attribute for the model that you can use to validate:

class Widget < ActiveRecord::Base attr_accessor :confirmation_email validates_length_of :confirmation_email, :within => 1..10 end 

To check only at a specific time, you can use the condition :if :

validates_length_of :confirmation_email, :within => 1..10, :if => Proc.new { |widget| widget.creation_step > 2 }

You can also use the class method, for example :if => :payment_complete . With their help, you can achieve the necessary functionality. As far as I know, there is no more concise way.

+3
source

Yehuda Katz has a great explanation on how you can use ActiveModel to make an arbitrary class compatible with Rails form helpers. This only works if you are using Rails 3.

If you don’t live on the verge of bleeding, check out the Railscasts 193 episode, “Tableless Model” , which describes how you can create a class that is quite a trick like ActiveRecord::Base that works with form_for .

+1
source

Source: https://habr.com/ru/post/1301762/


All Articles