У меня есть три модели: клиент, автомобиль и парковка. У клиента много автомобилей, а у автомобиля много парковочных мест. У меня есть форма на странице клиента, которая создает автомобиль, связанный с этим клиентом. Я не знаю, как это сделать, так это добавить поле для park_rate в эту форму, так что, когда автомобиль создан для этого клиента, для этого автомобиля также создается парковочный тариф.Rails 4: form_for с вложенной моделью
Мой код выглядит следующим образом:
client.rb
class Client < ActiveRecord::Base
has_many :cars, dependent: destroy
end
car.rb
class Car < ActiveRecord::Base
belongs_to :client
has_many :parking_rates
end
parking_rate.rb
class ParkingRate < ActiveRecord::Base
belongs_to :car
end
На странице клиента (клиент/: id), у меня есть форма для создания автомобиля ssociated с этим клиентом, как это:
просмотров/клиентов/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_controller.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
cars_controller.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
С этим я могу добавить машины к данному клиенту, но я также хотел бы добавить parking_rate к машине на одной и той же форме. Поэтому, когда я создаю автомобиль, используя эту форму, я хочу создать связанную парковку. Помощник form_for
использует объект [@client, @client.comments.build]
в качестве объекта модели, поэтому я не уверен, как ссылаться на модель parking_rate
в том же виде. Я думаю, что решение заключается в использовании помощника fields_for
, какова будет эталонная модель для этого, и что мне нужно будет добавить к машинам и клиентским контроллерам?
попытался с помощью 'accepts_nested_attributes_for: parking_rates, зависимое: destroy' в модели автомобилей. –
Чтение Rails Guides на [Forms] (http://guides.rubyonrails.org/form_helpers.html#building-complex-forms) может помочь вам. –