Mon proprety isn't a string?

G

Greg Ma

Hi,
I would simply like to remove spaces of the property "name" before save
and update.
So i did the code below, but i get this error when I save or update a
tag.
#error
undefined method `strip' for nil:NilClass



#Tag class
class Tag < ActiveRecord::Base
has_and_belongs_to_many :students

attr_accessible :name

validates_uniqueness_of :name

before_save :remove_spaces
before_update :remove_spaces

private
def remove_spaces
name = name.strip
end

end



This is how i save or update my tag
#From another class
def tag_attributes=(tags_att)
splits = tags_att.split(',')
splits.each do |tag|
if !tags.find_by_name(tag)
tags.build:)name => tag)
end
end
end
 
R

Rob Biedenharn

Hi,
I would simply like to remove spaces of the property "name" before
save
and update.
So i did the code below, but i get this error when I save or update a
tag.
#error
undefined method `strip' for nil:NilClass

#Tag class
class Tag < ActiveRecord::Base
has_and_belongs_to_many :students

attr_accessible :name

validates_uniqueness_of :name

before_save :remove_spaces
before_update :remove_spaces
before_save will catch both create and update
private
def remove_spaces
name = name.strip
self.name = self.name.strip

the "name = " part is enough to trick the interpreter into treating
'name' as a local rather than a bare method call. Using self.name
forces the treatment as a method.

-Rob
end

end



This is how i save or update my tag
#From another class
def tag_attributes=(tags_att)
splits = tags_att.split(',')
splits.each do |tag|
if !tags.find_by_name(tag)
tags.build:)name => tag)
end
end
end

Rob Biedenharn http://agileconsultingllc.com
(e-mail address removed)
 
B

Brian Candler

Or perhaps clearer:

def remove_spaces
name.strip!
end

If there's any chance that name could actually be nil, then

def remove_spaces
name.strip! if name
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,159
Messages
2,570,881
Members
47,418
Latest member
NoellaXku

Latest Threads

Top