how do I make changes to inpus from edit/update in Rails?
I have he following code in my update action for a Controller. The code works when in the create, but doesn't seem to kick in under update:
def update
@contact = Contact.find(params[:id])
# bug, why isn't this working?
unless @contact.fax.empty?
@contact.fax = "1" + Phony.normalize(@contact.fax)
end
unless @contact.phone.empty?
@contact.phone = "1" + Phony.normalize(@contact.phone)
end
if @contact.update_attri开发者_开发知识库butes(params[:contact])
flash[:notice] = "Successfully updated contact."
redirect_to @contact
else
render :action => 'edit'
end
end
these should be in your model. FAT model, SKINNY controller:
# contact.rb
...
# may need require 'phony' and include Phony
before_save :prep
def prep
self.fax = 1+Phony.normalize(self.fax) unless self.fax.empty? || (self.fax.length == 11 && self.fax[0] == 1)
self.phone = 1+Phony.normalize(self.phone) unless self.phone.empty? || (self.phone.length == 11 && self.phone[0] == 1)
end
...
Edit:
As I mentioned in my comment, it's better in terms of storage and efficiency and indexing to store as a bigint unsigned in your database and add the prettiness to the numbers in a method. This way, your site is always normalized (no two phone numbers will ever look different because they are formatted 'on the fly').
# sample methods
def phony
str = self.phone.to_s
"#{str[0..2]}-#{str[3..5]}-#{str[6..10]}"
end
# use a similar method for faxing, but I'll write
# this one differently just to show flexibility
def faxy
str = self.fax.to_s
"+1 (#{str[0..2]}) #{str[3..5]}-#{str[6..10]}"
end
you never call save
on @contact
in your unless
blocks, so your call to @contact.update_attributes(params[:contact])
undoes any change you made in those blocks (because those keys in the params
hash correspond to empty values).
def update
@contact = Contact.find(params[:id])
if @contact.update_attributes(params[:contact])
@contact.update_attributes(:fax => "1" + Phony.normalize(@contact.fax)) unless @contact.fax.empty?
@contact.update_attributes(:phone => "1" + Phony.normalize(@contact.phone)) unless @contact.phone.empty?
flash[:notice] = "Successfully updated contact."
redirect_to @contact
else
render :action => 'edit'
end
end
You could use update_attribute
but that bypasses validation.
You could also use a before_save
callback in the Contact
class, but you would have to check if the phone
or fax
are already "normalized."
精彩评论