I would like to strip all whitespace in some fields before they go into my database.
I am using devise and have added additional fields to the members table (used members instead of users).
On my sign up form I have some fields such as telephone and address however I would like to strip all whitespace for certain fields like :telephone, :mobile and :emergency_number.
Sounds like a job for before_save!
class Member < ActiveRecord::Base
before_save :strip_whitespace
private
def strip_whitespace
self.telephone.gsub!(/\s+/, '')
# etc...
end
end
An easy way to #Chowlett's solution
class Member < ActiveRecord::Base
before_save :strip_whitespace
private:
def strip_whitespace
self.telephone.join('')
# etc...
end
end
Related
Right now, I have some legacy classes with differently-named columns that I've aliased to a new, common name via Rails' alias_attribute, as below:
class User < ActiveRecord::Base
alias_attribute :id, :UserId
...
end
class Car < ActiveRecord::Base
alias_attribute :id, :CarId
...
end
For some logging purposes, I need to access the old column names (eg. CarId and UserId). Is there a general way to access the old name from alias_attribute via its alias? Renaming the old columns is not ideal, since many other parts of the app are still using the old column names.
alias_attribute is a very simple method. All it does is, well, define aliases.
def alias_attribute(new_name, old_name)
# The following reader methods use an explicit `self` receiver in order to
# support aliases that start with an uppercase letter. Otherwise, they would
# be resolved as constants instead.
module_eval <<-STR, __FILE__, __LINE__ + 1
def #{new_name}; self.#{old_name}; end # def subject; self.title; end
def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end
def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end
STR
end
So no, there's no way to retrieve the original column name.
I would like to add additional fields to the Rails Admin 'new' view for a specific model object, 'User'. These fields would not be attributes on the model itself but instead just fields that I would like users to be able to submit information with in order to calculate another field.
Is this possible?
Add virtual field to your model in rails admin using,
config.model Address do
list do
# virtual field
configure :full_address do
# any configuration
end
fields :full_address, :street, :number #, ...
end
end
Reference - https://github.com/sferik/rails_admin/wiki/Fields#virtual-fields
I'm not entirely familiar with Rails Admin, but you should be able to get what you want with Rails' virtual attributes mechanism.
In your user.rb model file, you need to add an attr_accessor line, listing the symbols you want to assign to your non-model fields, like this:
class User < ActiveRecord::Base
attr_accessor :virtual_field_one, :virtual_field_two
# Remainder of your code
end
You can add fields to the corresponding view that populate those values:
<%= f.text_field :virtual_field_one %>
Then you can add those attributes to the strong parameters method of your users_controller.rb, like this:
class ActivitiesController < ApplicationController
# other code
def user_params
params.require(:activity).permit(:mode_field_one, :mode_field_two, :virtual_field_one, :virtual_field_two)
end
# other code
end
Now you should be able to access virtual_field_one and virtual_field_two from the params hash like any other field in your User model:
virtual_field_one = params[:virtual_field_one]
I have two tables: admin_users and users. I want all the created names to be unique (a regular user can't create a name already taken by an admin user and vice-versa). I'm having trouble writing a validates_uniqueness_of validation that is able to analyze information in a different table. I think I have to use a scope of some sort, but I tried all sorts of combinations and couldn't get it to work. To be clear: I'm looking for the correct code to replace the question marks below.
validates_uniqueness_of :user_name, :scope => #???Look in admin users
#table and check to make that this name is not taken.
Any help would be very much appreciated. Thanks!
You can create a custom validator for this.
class UserNameValidator < ActiveModel::Validator
def validate(record)
if AdminUser.exists?(user_name: record.user_name)
record.errors[:base] << "An admin user have this username!"
end
end
end
class User < ActiveRecord::Base
validates_with UserNameValidator
end
I have a simple user table and i would like to add a new field to my user table that says permalink. This permalink would be updated with the following code for all the users
name.downcase.gsub(/[^0-9a-z]+/, ' ').strip.gsub(' ', '-'). I want to create a migration file that updates all the users permalink fields with the code above so that old users would have their permalink set and i would use an after_create method for new users.
I think you could try something like this:
class User < ActiveRecord::Base
before_create :set_permalink
def set_permalink
permalink = name.downcase.gsub(/[^0-9a-z]+/, ' ').strip.gsub(' ', '-')
end
end
This actually uses the before_create callback, which would address the deriving of the permalink field for new users. I think this is what you actually need.
And in your migration file ...
class UpdateUsersPermalink < ActiveRecord::Migration
def self.up
User.reset_column_information
User.all.each do |u|
if u.permalink.nil?
u.set_permalink
u.save!
end
end
end
...
end
.. which would take care of any existing Users that do not have this field set just yet.
I'm relatively new to Rails and a bit surprised this isn't a configurable behavior...at least not one I've been able to find yet?!? I would have thought that 99% of forms would benefit from whitespace being trimmed from all string & text fields?!? Guess I'm wrong...
Regardless, I'm looking for a DRY way to strip all whitespace from form fields (of type :string & :text) in a Rails 3 app.
The Views have Helpers that are automatically referenced (included?) and available to each view...but Models don't seem to have such a thing?!? Or do they?
So currently I doing the following which first requires and then includes the whitespace_helper (aka WhitespaceHelper). but this still doesn't seem very DRY to me but it works...
ClassName.rb:
require 'whitespace_helper'
class ClassName < ActiveRecord::Base
include WhitespaceHelper
before_validation :strip_blanks
...
protected
def strip_blanks
self.attributeA.strip!
self.attributeB.strip!
...
end
lib/whitespace_helper.rb:
module WhitespaceHelper
def strip_whitespace
self.attributes.each_pair do |key, value|
self[key] = value.strip if value.respond_to?('strip')
end
end
I guess I'm looking for a single (D.R.Y.) method (class?) to put somewhere (lib/ ?) that would take a list of params (or attributes) and remove the whitespace (.strip! ?) from each attribute w/out being named specifically.
Create a before_validation helper as seen here
module Trimmer
def trimmed_fields *field_list
before_validation do |model|
field_list.each do |n|
model[n] = model[n].strip if model[n].respond_to?('strip')
end
end
end
end
require 'trimmer'
class ClassName < ActiveRecord::Base
extend Trimmer
trimmed_fields :attributeA, :attributeB
end
Use the AutoStripAttributes gem for Rails. it'll help you to easily and cleanly accomplish the task.
class User < ActiveRecord::Base
# Normal usage where " aaa bbb\t " changes to "aaa bbb"
auto_strip_attributes :nick, :comment
# Squeezes spaces inside the string: "James Bond " => "James Bond"
auto_strip_attributes :name, :squish => true
# Won't set to null even if string is blank. " " => ""
auto_strip_attributes :email, :nullify => false
end
Note I haven't tried this and it might be a crazy idea, but you could create a class like this:
MyActiveRecordBase < ActiveRecord::Base
require 'whitespace_helper'
include WhitespaceHelper
end
... and then have your models inherit from that instead of AR::Base:
MyModel < MyActiveRecordBase
# stuff
end