所以我被困在这几个小时。我有一个有很多通过关联的应用程序,我正在尝试将父资源的id
传递给孩子。路由确实有效,我可以浏览甚至创建新对象,但是url并没有显示路径中的id。
预期&期望的结果
http://127.0.0.1:3000/locations/1/groups/1/products/1
当前结果
http://127.0.0.1:3000/locations/location/groups/group/products/1
的routes.rb
...
resources :locations do
resources :groups do
resources :products
end
end
...
products_controller.rb 我的所有控制器都设置与此类似。
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
def index
@locations = Location.all
@products = Product.all
@groups = Group.all
end
def show
@product = Product.find(params[:id])
end
def new
@product = Product.new
end
def edit
@product = Product.find(params[:id])
end
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to location_group_products_path(@product), notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: @product }
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @product.update(product_params)
format.html { redirect_to location_group_product_path(@product), notice: 'Product was successfully updated.' }
format.json { render :show, status: :ok, location: @product }
else
format.html { render :edit }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
def destroy
@product.destroy
respond_to do |format|
format.html { redirect_to location_group_products_path(@product), notice: 'Product was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_product
@product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:name, :location_id, :group_id, :product_id)
end
end
products.html.rb
<h1>Products</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @products.each do |product| %>
<tr>
<td><%= product.name %></td>
<td><%= link_to 'Show', location_group_product_path(:location, :group, product) %></td>
<td><%= link_to 'Edit', edit_location_group_product_path(:location, :group, product.id) %></td>
<td><%= link_to 'Destroy', location_group_product_path(:location, :group, product.id), method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Product', new_location_group_product_path %>
答案 0 :(得分:0)
您应该传递位置和组的ID(或对象)而不仅仅是它们的符号。像这样:
location_group_product_path(product.group.location, product.group, product)
edit_location_group_product_path(product.group.location, product.group, product)