Rails 4:form_for与嵌套模型

时间:2013-09-05 10:22:54

标签: ruby-on-rails nested-form-for

我有三种型号:Client,Car和ParkingRate。客户有很多车,车有很多停车位。我在客户端页面上有一个表单,用于创建与该客户端关联的汽车。我不知道该怎么做是为该表单添加一个parking_rate字段,这样当为该客户创建汽车时,还会为该汽车创建停车费率。

我的代码如下:

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

在客户端页面(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_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帮助器,那将是什么样的模型参考,以及我需要将哪些内容添加到汽车和客户端控制器?

1 个答案:

答案 0 :(得分:0)

在client.rb中,添加行

accepts_nested_attributes_for :cars