我希望能得到一些帮助来解决一个我相信你们中的许多人可以在睡眠中避免的问题。
我有两个处于 habtm 关系的模型。一个包可以有多个位置,一个位置可以有多个包。如果我的位置模型验证失败(例如,由于位置地址为空),我会收到 ActiveRecord:RecordInvalid 异常。我知道我收到此错误是因为当我调用 package.save 时,rails 会自动调用 save!关于位置关联。
我不确定如何避免错误或至少挽救错误。关于如何解决问题和 Rails 最佳实践,你们有什么好的建议吗?
这是代码:
def create
@package = current_user.package.build(params[:package])
package_location
if @package.save
flash[:success] = "Package created!"
redirect_to root_path
else
render 'pages/home'
end
end
def package_location
gps_processing if !session[:gps_aware]
@package.locations.build(:address => session[:address])
end
def gps_processing
session[:address] = [params[:story][:street_address], params[:story][:city], params[:story][:state], params[:story][:country]].compact.join(', ')
end
class Package< ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :locations
validates :content, :presence => true,
:length => {:maximum => 140}
validates :user_id, :presence => true
default_scope :order => 'package.created_at DESC'
end
class Location < ActiveRecord::Base
attr_accessible :lng, :lat, :address
validates :lng, :presence => true
validates :lat, :presence => true
validates :address, :presence => true
geocoded_by :full_street_address, :latitude => :lat, :longitude => :lng
before_validation :geocode
has_and_belongs_to_many :packages
def full_street_address
address
end
end
` 提前感谢您的帮助!