我有三个模型:Client、Car 和 ParkingRate。客户有很多汽车,汽车有很多停车费率。我在客户端页面上有一个表单,用于创建与该客户端关联的汽车。我不知道如何在该表单中添加一个 park_rate 字段,以便在为该客户创建汽车时,也会为该汽车创建停车费率。
我的代码如下所示:
客户端.rb
class Client < ActiveRecord::Base
has_many :cars, dependent: destroy
end
碳水化合物
class Car < ActiveRecord::Base
belongs_to :client
has_many :parking_rates
end
停车费率.rb
class ParkingRate < ActiveRecord::Base
belongs_to :car
end
在客户端页面 (client/:id) 上,我有一个表单来创建与该客户端关联的汽车,如下所示:
意见/客户/show.html.erb:
<h1>Client information</h1>
... client info ...
<%= render 'cars/form' %>
意见/汽车/_form.html.erb:
<%= form_for([@client, @client.cars.build]) do |f| %>
<p>
<%= f.label :vehicle_id_number %><br>
<%= f.text_field :vehicle_id_number %>
</p>
<p>
<%= f.label :enter_date %><br>
<%= f.text_field :enter_date %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
Clients 和 Cars 控制器如下所示:
客户控制器.rb:
class ClientsController < ApplicationController
def new
@client = Client.new
end
def create
@client = Client.new(client_params)
if @client.save
redirect_to @client
else
render 'new'
end
end
def show
@client = Client.find(params[:id])
end
def index
@clients = Client.all
end
def edit
@client = Client.find(params[:id])
end
def update
@client = Client.find(params[:id])
if @client.update(client_params)
redirect_to @client
else
render 'edit'
end
end
def destroy
@client = Client.find(params[:id])
@client.destroy
redirect_to clients_path
end
private
def client_params
params.require(:client).permit(:first_name, :last_name)
end
end
汽车控制器.rb:
class CarsController < ApplicationController
def create
@client = Client.find(params[:client_id])
@car = @client.cars.create(car_params)
@parking_rate = @car.parking_rates.create(rate_params)
redirect_to client_path(@client)
end
def show
@client = Client.find(params[:client_id])
@car = Car.find(params[:id])
end
def edit
@client = Client.find(params[:client_id])
@car = Car.find(params[:id])
end
def update
@client = Client.find(params[:client_id])
@car = Car.find(params[:id])
@car.update(car_params)
redirect_to client_path(@client)
end
def destroy
@client = Client.find(params[:client_id])
@car = @client.cars.find(params[:id])
@car.destroy
redirect_to client_path(@client)
end
private
def car_params
params.require(:car).permit(:vehicle_id_number, :enter_date, :rate)
end
def rate_params
params.require(:parking_rate).permit(:rate)
end
end
有了这个,我可以将汽车添加到给定的客户,但我也想在同一个表单上为汽车添加停车费率。因此,当我使用此表单创建汽车时,我想创建一个相关的停车费。form_for
助手使用 a作为[@client, @client.comments.build]
模型对象,所以我不确定如何以parking_rate
相同的形式引用模型。我认为解决方案是使用fields_for
帮助器,模型参考是什么,我需要向汽车和客户端控制器添加什么?