What is the best place to use to process form data before saving it in Rails 3?

In terms of rails best practices, what is the best way to manipulate form data before saving?

For instace, in the contact form, I want all the data to be saved in the header form (do you hate it when the PEOPLE SHOUT AT YOU is in the form "please contact me"? :-))

  • is it better to manipulate the controller? Could I either do this in the creation, or move it to some private method that will use all the string attributes of the object before saving / updating?

Or

  • is the before_save model better? It makes sense to me that this should be done in the model, since I probably want it to be the same for all records, regardless of whether I manipulate them in the rake solution or through the web interface.

Bonus:

Also, where would I put it if I want on ALL of my models with the ability to override defaults in each case? Application controller? There may be some special cases where you want to preserve value without a capital letter - that is, brand products that are not used (i.e. Utorrent) or a surname that should have several caps in the name (for example, Irish and Scottish names, such like McDonald)

Thank!

+3
source share
3 answers

, , :

/clean _strings.rb

module ActiveRecord
  class Base
    attr_accessor :dont_capitlize, :dont_strip

    before_save :_capitalize_strings, :unless => :dont_capitlize
    before_save :_strip_whitespaces,  :unless => :dont_strip

    def _capitalize_strings
      self.attributes.each_pair do |key, value|
        self[key] = value.capitalize if value.respond_to?('capitalize')
      end
    end


    def _strip_whitespaces
      self.attributes.each_pair do |key, value|
        self[key] = value.strip if value.respond_to?('strip')
      end
    end

  end
end

environment.rb

require "clean_strings"

,

@a.dont_capitalize = true
@a.save!

( , ). , , , . , , , , , CAPS LOCK!!!

( ).

0

, . before_save, before_validation, , . - :

before_save :upcase_content

def upcase_content
  self.content = self.content.upcase
end

, , attr_accessor .

class MyModel < ActiveRecord::Base
attr_accessor :dont_upcase

before_save :upcase_content, :unless => :dont_upcase
...
end

true

@model = Model.new(:brand_name => utorrent)
@model.dont_upcase = true
@model.save!
+4

The best place to put this in your model is, so you have a thick model and a skinny controller, which is the “good thing”.

If you want this to be available for all your models, my suggestion is to use a module that contains your common functions, and then include it in all the models that you want to use by default.

+3
source

All Articles