【发布时间】:2020-02-15 17:23:22
【问题描述】:
我遇到了一个奇怪的问题。我的应用程序中有两个模型,市区和属性。市中心应该有多个房产,房产应该有一个市中心。
在我的市中心展示页面上,我会遍历每个市中心的房产,然后提供指向这些房产的链接。
问题是.....当我点击每个属性时,网址会倒退。 IE,一个ID为1的市区和一个ID为8的房产应该去
downtown/1/properties/8
但它仍在继续
downtown/8/properties/1
我觉得这太奇怪了,我不知道我在这里做错了什么。
在我的市中心展示页面上,我循环浏览了每个属性
%h2= @downtown.name
- if @downtown.properties.present?
%p
- @downtown.properties.collect do |property|
= link_to property.name, downtown_property_path(property)
- else
No downtowns for now.
我的路由是这里的基本嵌套路由
resources :downtowns do
resources :properties
end
我的属性控制器是
class PropertiesController < Downtown::ApplicationController
before_action :find_property, only: [:show, :edit, :update, :destroy]
def new
@property = @downtown.properties.new
end
def create
@property = @downtown.properties.new(property_params)
if @property.save
redirect_to @downtown
else
render :new
end
end
def show
end
private
def property_params
params.require(:property).permit(:name, :downtown, :downtown_id......)
end
def find_property
@property = Property.find(params[:id])
end
end
我的市区控制器是
class DowntownsController < ApplicationController
before_action :find_downtown, only: [:show, :edit, :update, :destroy]
def show
@properties = Property.where(downtown: @downtown_id)
end
def new
@downtown = Downtown.new
end
def create
@downtown = Downtown.create(downtown_params)
if @downtown.save
redirect_to @downtown
else
render 'new'
end
end
private
def downtown_params
params.require(:downtown).permit(:name, :city)
end
def find_downtown
@downtown = Downtown.find(params[:id])
end
end
最后在我的属性表单中我有一个多态路径
= simple_form_for([@property, @downtown]) do |f|
= f.input :name
= f.input :last_remodel
= f.input :original_construction_year
【问题讨论】:
-
如果它是一个嵌套路由,它可能应该将@downtown 作为第一个参数:
downtown_property_path(@downtown, property) -
我还建议您查看Rails Routing from the Outside In 指南中的Shallow Nesting 部分。
标签: ruby-on-rails ruby routing simple-form