如何从Rails中的编辑/更新中更改inpus?

Tim*_* T. 1 activerecord model ruby-on-rails

我在控制器的更新操作中跟随代码.代码在创建时有效,但似乎没有在更新下启动:

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_attributes(params[:contact])
   flash[:notice] = "Successfully updated contact."
   redirect_to @contact
 else
   render :action => 'edit'
 end
Run Code Online (Sandbox Code Playgroud)

结束

set*_*rgo 6

这些应该在你的模型中.FAT模型,SKINNY控制器:

# 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
...
Run Code Online (Sandbox Code Playgroud)

编辑:

正如我在评论中提到的那样,在存储和效率以及索引方面,最好将其作为未签名的bigint存储在数据库中,并为方法中的数字添加美观.这样,您的网站始终被标准化(没有两个电话号码看起来会有所不同,因为它们是"即时"格式化的).

# 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
Run Code Online (Sandbox Code Playgroud)