我正在使用RoR 6创建一个API项目。我有以下模型:
class Province < ApplicationRecord
validates :province, presence: true, length: {minimum:5}, uniqueness: true
has_many :cities, dependent: :destroy
end
class City < ApplicationRecord
validates :city, presence: true, length: {minimum: 5}, uniqueness: true
belongs_to :province
end
迁移:
class CreateProvinces < ActiveRecord::Migration[6.1]
def change
create_table :provinces do |t|
t.string :province
t.timestamps
end
end
end
class CreateCities < ActiveRecord::Migration[6.1]
def change
create_table :cities do |t|
t.string :city
t.references :province, null: false, foreign_key: true
t.timestamps
end
end
end
def create
@city = City.new(city_params)
if @city.save
render json: @city, status: :created, location: @city
else
render json: @city.errors, status: :unprocessable_entity
end
end
private
def city_params
params.require(:city).permit(:city, :province_id)
end
Rails.application.routes.draw do
resources :provinces, defaults: { format: :json } do
resources :cities, defaults: { format: :json }
end
end
curl --location --request POST 'http://127.0.0.1:3000/provinces/1/cities' \
--header 'Content-Type: application/json' \
--data-raw '{
"city": "New City",
"province": 1
}'
{“省”:[“必须存在”]}
p=Province.find(1)
c=City.new({city: 'New City', province: p})
c.save