【发布时间】:2021-02-20 14:25:42
【问题描述】:
我正在做一些重构,我已经看过这个项目一段时间了,从我上次回忆的情况来看,它确实有效。但问题是,我正在尝试创建一个航班,但在尝试时我不断收到“ActiveModel::MissingAttributeError (can't write unknown attribute flights_count):”创建一个新的航班。
就我的模型而言:
我的飞行,飞行员模型
class Flight < ActiveRecord::Base
has_many :passengers
belongs_to :destination
belongs_to :pilot, counter_cache: true
accepts_nested_attributes_for :passengers
belongs_to :user, class_name: "Flight" ,optional: true
validates_presence_of :flight_number
validates :flight_number, uniqueness: true
scope :order_by_flight_international, -> { order(flight_number: :asc).where("LENGTH(flight_number) > 3") }
scope :order_by_flight_domestic, -> { order(flight_number: :asc).where("LENGTH(flight_number) <= 2 ") }
def dest_name=(name)
self.destination = Destination.find_or_create_by(name: name)
end
def dest_name
self.destination ? self.destination.name : nil
end
def pilot_name=(name)
self.pilot = Pilot.find_or_create_by(name: name)
end
def pilot_name
self.pilot ? self.pilot.name : nil
end
end
class Pilot < ActiveRecord::Base
belongs_to :user, optional: true
has_many :flights
has_many :destinations, through: :flights
validates_presence_of :name, :rank
validates :name, uniqueness: true
scope :top_pilot, -> { order(flight_count: :desc).limit(1)}
end
编辑 飞行控制器
class FlightsController < ApplicationController
before_action :verified_user
layout 'flightlayout'
def index
@flights = Flight.order_by_flight_international
@dom_flights = Flight.order_by_flight_domestic
end
def new
@flight = Flight.new
10.times {@flight.passengers.build}
end
def create
@flight = Flight.new(flight_params)
# byebug
if @flight.save!
redirect_to flight_path(current_user,@flight)
else
flash.now[:danger] = 'Flight Number, Destination, and Pilot have to be selected at least'
render :new
end
end
private
def flight_params
params.require(:flight).permit(:flight_number,:date_of_flight, :flight_time, :flight_id, :destination_id, :pilot_id, :pilot_id =>[], :destination_id =>[], passengers_attributes:[:id, :name])
end
end
编辑 航班、试点模式
create_table "flights", force: :cascade do |t|
t.integer "pilot_id"
t.integer "destination_id"
t.string "flight_number"
t.string "date_of_flight"
t.string "flight_time"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "pilots", force: :cascade do |t|
t.string "name"
t.string "rank"
t.integer "user_id"
t.integer "flight_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "flight_count", default: 0
end
正如我上次在这个项目上工作时所说的,一切正常,但我面临这个问题。这次我做错了什么。
【问题讨论】:
-
向我们展示您的控制器和该表的架构
-
@ZainArshad 我刚刚为你更新了
-
Detination_id 和 Pilot_id 在您的 flight_params 中被使用了两次,是故意的吗?
-
不是意外
-
我在您的模型航班架构中看不到 flight_count 属性,您的模型中也没有 flight_count 方法。你有那个吗?
标签: ruby-on-rails ruby