我正在开发一个用作飞机日志的应用程序。我的数据库设计可能会朝着错误的方向前进。对此的任何建议都会很有用。这是嵌套表单的情况吗?还是仅当我需要同时为两个模型创建记录时?
到目前为止,这就是我布置模型的方式:
class Location < ActiveRecord::Base
has_many :aircrafts, :pilots
end
class Aircraft < ActiveRecord::Base
belongs_to :location
has_many :trips
end
class Pilot < ActiveRecord::Base
belongs_to :location
has_many :trips
end
class Trip < ActiveRecord::Base
belongs_to :aircraft, :pilot
end
ActiveRecord::Schema.define(:version => 20120209014016) do
create_table "aircrafts", :force => true do |t|
t.string "tail_number"
t.decimal "hobbs"
t.integer "location_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "aircrafts", ["location_id"], :name => "index_aircrafts_on_location_id"
create_table "locations", :force => true do |t|
t.string "city"
t.string "state"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "pilots", :force => true do |t|
t.string "first_name"
t.string "last_name"
t.string "email"
t.integer "location_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "pilots", ["location_id"], :name => "index_pilots_on_location_id"
create_table "trips", :force => true do |t|
t.date "date"
t.integer "aircraft_id"
t.decimal "hobbs_out"
t.decimal "hobbs_in"
t.integer "cycles_airframe"
t.integer "cycles_left"
t.integer "cycles_right"
t.time "time_out"
t.time "time_in"
t.integer "pic_id"
t.integer "sic_id"
t.string "flight_sequence"
t.text "remarks"
t.integer "miles"
t.datetime "created_at"
t.datetime "updated_at"
end
end
我想要做的是创建一个新的旅行记录并更新飞机记录中的 :hobbs 列。使用 Aircraft 表,我基本上想跟踪当前的 hobbs 时间(或将其视为汽车的当前里程)。当我创建一个新的行程时,它将使用当前的 hobbs 时间作为 hobbs_out 属性,并且 hobbs_in 将记录在行程中并用于更新 Aircraft.hobbs。
我可以使用trip_controller 中的代码执行此操作吗?就像是:
def create
@trip = Trip.new(params[:trip])
@aircraft = Aircraft.where(params[:trip][:aircraft_id])
@aircraft.hobbs = params[:trip][:hobbs_in]
@aircraft.save
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
如果它更像是嵌套表单的情况,我将如何让表单只更新飞机记录并创建新的行程记录?
谢谢!