我希望得到一些帮助解决一个问题,我相信你们中的许多人可以在睡梦中避免.
我有两个关系模式.一个包可以有很多位置,一个位置可以有很多包.如果我的位置模型验证失败(例如,由于位置地址为空),我会得到anActiveRecord: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, …Run Code Online (Sandbox Code Playgroud)