我有两个模型,Trips和Locations。旅行的起点和目的地都是对位置的引用:
class Trip < ActiveRecord::Base
attr_accessible :name, :destination, :origin, :start_datetime, :transportation, :trip_type, :destination_attributes, :origin_attributes
enum_attr :trip_type, %w(Hitchhiker Driver)
has_one :origin, :class_name => 'Location' , :primary_key => :origin, :foreign_key => :id
has_one :destination, :class_name => 'Location' , :primary_key => :destination, :foreign_key => :id
accepts_nested_attributes_for :origin, :allow_destroy => true
accepts_nested_attributes_for :destination, :allow_destroy => true
belongs_to :user
validates_presence_of :name, :destination, :origin, :start_datetime, :transportation, :trip_type
end
class Location < ActiveRecord::Base
attr_accessible :address, :latitude, :longitude
geocoded_by :address
before_validation :geocode
validates_presence_of :address
validate :geocoding_was_found
def geocoding_was_found
errors.add(:address, 'is not valid') if latitude.nil? || longitude.nil?
end
end
在控制器中调用create时,它会保存所有记录(两个位置记录和行程记录),但不保存关联。
def create
@trip = Trip.new(params[:trip])
@trip.user = current_user
respond_to do |format|
if @trip.save
format.html { redirect_to @trip, notice: 'Trip was successfully created.' }
format.json { render json: @trip, status: :created, location: @trip }
else
format.html { render action: "new" }
format.json { render json: @trip.errors, status: :unprocessable_entity }
end
end
end
我正在使用嵌套表单,因此通过origin_attributes和destination_attributes传递location的数据。我的猜测是因为这两个字段被称为origin和destination而不是_id。