0
所以,以下是我定義我的應用程序的路由方式:如何在rails中通過嵌套路由創建新對象?
Rails.application.routes.draw do
resources :operators do
resources :cabs
end
end
如所理解的,我的應用程序有一些出租車運營商和每個運營商都有駕駛室一定數量的與他們有聯繫:
class Operator < ActiveRecord::Base
has_many :cabs
end
當我試圖創建一個新的駕駛室,因爲這個問題是:
<%= link_to 'New Cab', new_operator_cab_path %>
新型駕駛室創作形式如下:
<%= form_for @cab, url: operator_cabs_path, method: :post do |f| %>
<% if @cab.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@cab.errors.count, "error") %> prohibited this cab from being saved:</h2>
<ul>
<% @cab.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :category %><br>
<%= f.text_field :category %>
</div>
<div class="field">
<%= f.label :number %><br>
<%= f.text_field :number %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我不得不顯式定義url和表單中的方法,默認url(cabs_path)根據路由定義的方式不存在。 雖然我的鏈接工作正常,但沒有新的駕駛室被創建。以下是我的cabs_controller:
class CabsController < ApplicationController
before_action :set_cab, only: [:show, :edit, :update, :destroy]
# GET /cabs
# GET /cabs.json
def index
@cabs = Operator.find(params[:operator_id]).cabs
end
# GET /cabs/1
# GET /cabs/1.json
def show
end
# GET /cabs/new
def new
@cab = Cab.new
@operator = Operator.find(params[:operator_id])
end
# GET /cabs/1/edit
def edit
@operators = Operator.all
end
# POST /cabs
# POST /cabs.json
def create
@cab = Cab.new(cab_params)
respond_to do |format|
if @cab.save
format.html { redirect_to operator_cabs_path, notice: 'Cab was successfully created.' }
format.json { render :show, status: :created, location: @cab }
else
format.html { render :new }
format.json { render json: @cab.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /cabs/1
# PATCH/PUT /cabs/1.json
def update
respond_to do |format|
if @cab.update(cab_params)
format.html { redirect_to operator_cabs_path(operator_id: @operator.id), notice: 'Cab was successfully updated.' }
format.json { render :show, status: :ok, location: @cab }
else
format.html { render :edit }
format.json { render json: @cab.errors, status: :unprocessable_entity }
end
end
end
# DELETE /cabs/1
# DELETE /cabs/1.json
def destroy
@cab.destroy
respond_to do |format|
format.html { redirect_to operator_cabs_path(operator_id: @operator.id), notice: 'Cab was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cab
@cab = Cab.find(params[:id])
@operator = Operator.find(params[:operator_id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def cab_params
params.require(:cab).permit(:category, :number)
end
end
聽起來像是你想使用類似@ operator.cabs.build_cab(cab_params)如果你希望操作員'擁有'駕駛室。參考克里斯的回答所需的協會 – Peege151 2014-11-09 08:19:39