我有两个模型,Trips 和 Locations。一次旅行有起点和终点,它们都是对 Location 的引用:
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 传递。我的猜测是因为这两个字段被称为起点和终点而不是_id。