Capitalizing Names before creation. Devise - ruby-on-rails

I am trying to get my user model to capitalize all names when a user signs up. It doesn't appear to the working however. I am using devise.
There is a name field in the database.
user model:
before_create :capitalize_name
def capitalize_name
name_array = name.split(" ")
name_array.each { |name| name.capitalize! }
name = name_array.join(" ")
end

The problem is that you assign the result to the local variable name. Use self.name.
self.name = name.split.map(&:capitalize).join(' ')

Try
self.name = name_array.join(" ")

Related

How to convert string to existing attribute in model when creation

I got a array of strings, I want to retrieve for each the attribute during the creation of the post.
My array = ["_646_maturity", "_660_maturity", "_651_maturity", "_652_maturity", "_641_maturity"]
class Audit < ApplicationRecord
belongs_to :user
before_save :calculate_scoring
def calculate_scoring
scoring = []
models = ActiveRecord::Base.connection.tables.collect{|t| t.underscore.singularize.camelize.constantize rescue nil}
columns = models.collect{|m| m.column_names rescue nil}
columns[2].each do |c|
if c.include? "maturity"
Rails.logger.debug 'COLUMN : '+c.inspect
scoring.push(c)
end
end
getMaturity = ""
scoring.each do |e|
getMaturity = e.to_sym.inspect
Rails.logger.debug 'MATURITY : '+getMaturity
end
end
end
The log print > 'MATURITY : :_651_maturity'
I'm looking to the value of :_651_maturity who is a attribute of my post.
I tried .to_sym but it's not working..
Thanks for the help!
Inside calculate_scoring you can use self to point to the record you are saving. So self._651_maturity = <some_value>, self[:_651_maturity] = <some_value> and self['_651_maturity'] are all valid methods to set _651_maturity.
Also, you can do something like:
my_attrib = '_651_maturity'
self[my_attrib] = 'foo'

Check whether a string contains numbers

I have input values like:
string = "devid"
string = "devid123"
string = "devid.123.devid"
I need to sort strings that contain .(number)., for example "devid.123.devid". How can I separate only strings that consist of .(numbers). like .123.? Help me find a solution.
In a controller, I have:
#person = Person.new
personname = params['personname']
if personname.match("/\d+/")
#person.person_name = personname
#person.save()
result = 'true'
end
When I execute this code, I get "devid123" and "devid.123.devid".
If its certain that the format of the valid personname is always
<string>.<number>.<string>
You can try using :[regex, index] method for strings in ruby.
https://ruby-doc.org/core-2.6.1/String.html#method-i-5B-5D
So if
personname = "devid.123.devid"
s[/(.*)(\.\d+\.)(.*)/, 2] = ".123."
There are three different groups in the regex (.*)(\.\d+\.)(.*).
Matches anything
Matches a .<number>.
Matches anything
So based on this regex, the second group should provide you .<number>. which, I hope, is what you need.
Tested with Ruby 2.4.1
If I understand this correctly you only want a string where the digits are preceded by .. If so you need to modify your regex to be /\.\d+/
#person = Person.new
personname=params['personname']
if personname.match("/\.\d+/")
#person.person_name = personname
#person.save
result = 'true'
end
But this sounds like logic you should be handling in the model, since this is tagged as rails and not plain old ruby
controller
class PersonController
def create
if #person = Person.create(params)
result = 'true'
else
result = 'false'
end
# whatever you doing with result
end
end
person.rb
class Person < ApplicationRecord
validates :personname, format: { with: /\.\d+\./, message: 'must include digits' }
end
You can play with the regex # rubular

I am getting error undefined method `to_sym' for nil:NilClass in Rails for updating image?

My controller
def update
handled_error_fields %i(location address1 address2 name name_kanji gender prefecture_code tel zip_code).collect { |s| :"primary_address.#{s}" }
if params[:salon].present?
if params[:salon].present?
if params[:salon][:tel].present?
tel = params[:staff][:tel]
params[:staff][:tel] = NKF.nkf('-W -w -m0 -Z0', tel)
end
end
if params[:staff][:email].present?
email = params[:staff][:email]
email.gsub!(/。/, '.')
params[:staff][:email] = NKF.nkf('-W -w -m0 -Z0', email)
end
end
if params[:staff]["staff_image"].present?
#staff_image = StaffImage.find_by_staff_id(current_staff.id)
if #staff_image.blank?
#staff_image = StaffImage.new
#staff_image.staff_id = current_staff.id
#staff_image.legacy_user_id = current_staff.legacy_user_id
#staff_image.image = params[:staff]["staff_image"]["image"].read
#staff_image.save!
else
#staff_image.image = params[:staff]["staff_image"]["image"].read
#staff_image.update_attribute('image', #staff_image.image)
end
end
super
end
My Model is
class StaffImage < ActiveRecord::Base
end
it has columns
staff_id,
image,
legacy_client_id.
Real problem is after insertion of image in database, I can't update the image. I am new to Rails. I know problem is in this line:
#staff_image.update_attribute('image', #staff_image.image)
Not using any attachment plugins? Have a look on https://github.com/thoughtbot/paperclip gem. Way too easy for handle this kind of things in Rails.
Not necessary to use update_attribute method. Simple save could solve.
#staff_image.image = params[:staff]["staff_image"]["image"].read
#staff_image.save
You might want to try calling "with_indifferent_access" like:
params = params.with_indifferent_access
before accessing "staff_image"
params[:staff]["staff_image"]["image"]
this should get rid of the error and then:
#staff_image.image = params[:staff]["staff_image"]["image"].read
#staff_image.save

Rails: Updating two fields of an ActiveRecord instance simultaniously

I have a model, called Book, that has the fields title and filename (and other fields but they are unrelated). I'd like that the filename field was automatically created using the title, thus in my Book.rb:
class Book < ActiveRecord::Base
# ...
def title=(title)
self.filename = sanitize_filename(title)
self.title = title
end
# ...
end
Because of self.title = title it's going in a infinite recursion. How could I avoid that?
Thanks!
You can write that on before_save
def before_save
self.filename = sanitize_filename(self.title)
end
Try this way
class Book
def title=(title)
self.filename = sanitize_filename(title)
self[:title] = title
end
end
There's a section in the ActiveRecord api on 'overwriting default accessors'. The suggested solution there is:
def title=(t)
self.filename = sanitize_filename(t)
write_attribute(:title, t)
end

Create new row after saving a record

A user submits a url, this is put into into article.url through the scaffold create method. I can parse the url like so:
def parse_url
elements = #article.url.split("/")
if(elements[0] == "http:")
#home = elements[2] #elements[1] will be an empty string because of the // in the URL
else
#home = elements[0]
end
end
What I would prefer to do is to parse the url after the user saves it with the create method and then insert this value into a new row in the database in the article table.
I'd use something like the following:
class Article
attr_accessor :unparsed_url
before_validation_on_save :parse_url
private
def parse_url
return unless unparsed_url
elements = unparsed_url.split("/")
if(elements[0] == "http:")
self.home = elements[2]
else
self.home = elements[0]
end
end
end
You'd use unparsed_url in the Rails forms. Using a virtual attribute like this will work nicely with form validation.

Resources