Ruby on rails Rails:嵌套模型不保存关联
我有两种型号,旅行和地点。行程有一个起点和一个终点,两者都是对位置的参考:Ruby on rails Rails:嵌套模型不保存关联,ruby-on-rails,activerecord,nested-forms,nested-attributes,Ruby On Rails,Activerecord,Nested Forms,Nested Attributes,我有两种型号,旅行和地点。行程有一个起点和一个终点,两者都是对位置的参考: class Trip < ActiveRecord::Base attr_accessible :name, :destination, :origin, :start_datetime, :transportation, :trip_type, :destination_attributes, :origin_attributes enum_attr :trip_type, %w(Hitchhiker
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
我使用的是嵌套表单,因此位置数据是通过原点属性和目标属性传入的。我猜这是因为这两个字段被称为origin和destination,而不是_id。使用has_one关系,每个位置只能属于一次旅行。另外,位置应该在attr_accessibleOk中有trip_id,但我希望有一个旅行的起点和目的地。出发地和目的地之间需要有很多关系吗?我认为你需要掌握主键和外键。当然,您不需要将这些更改为具有许多关系的
。旅行需要一个起点id
和一个“目的地id”,这应该可以正常工作。我会尝试并给出一个真实的答案,但其他人可以。我想那是票。
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