使用嵌套的路由和關聯。我有一個創建租戶的部分,但在創建之後,它會保留呈現的表單並且URL會更改爲/ tenant。期望的行爲是它需要重定向到顯示頁面。路線如下:用戶提交後不直接顯示頁面的Rails
Rails.application.routes.draw do
devise_for :landlords
authenticated :landlord do
root "properties#index", as: "authenticated_root"
end
resources :tenants
resources :properties do
resources :units
end
root 'static#home'
end
到目前爲止,性質和單位的工作(與房東)問題是租戶。原來我有租戶嵌套在單位下,但也有問題。部分看起來像這樣:
<%= form_for @tenant do |f| %>
<%= f.label "Tenant Name:" %>
<%= f.text_field :name %>
<%= f.label "Move-in Date:" %>
<%= f.date_field :move_in_date %>
<%= f.label "Back Rent Amount:" %>
$<%= f.text_field :back_rent %>
<%= f.button :Submit %>
<% end %>
<%= link_to "Cancel", root_path %>
租戶控制器看起來是這樣的:
before_action :authenticate_landlord!
#before_action :set_unit, only: [:new, :create]
before_action :set_tenant, except: [:new, :create]
def new
@tenant = Tenant.new
end
def create
@tenant = Tenant.new(tenant_params)
if @tenant.save
redirect_to(@tenant)
else
render 'new'
end
end
def show
end
def edit
end
def update
if @tenant.update(tenant_params)
redirect_to unit_tenant_path(@tenant)
else
render 'edit'
end
end
def destroy
end
private
def set_property
@property = Property.find(params[:property_id])
end
def set_unit
@unit = Unit.find(params[:unit_id])
end
def set_tenant
@tenant = Tenant.find(params[:id])
end
def tenant_params
params.require(:tenant).permit(:name, :move_in_date, :is_late, :back_rent, :unit_id)
end
end
型號有關聯:
class Tenant < ApplicationRecord
belongs_to :unit, inverse_of: :tenants
end
class Unit < ApplicationRecord
belongs_to :property, inverse_of: :units
has_many :tenants, inverse_of: :unit
end
最後的抽傭路線秀#租戶是:
tenant GET /tenants/:id(.:format) tenants#show
我有廣泛搜索這個話題,但沒有取得任何成功。任何幫助表示讚賞。 Rails的5.1
我最終改變了一些東西。我認爲我的主要問題是路由。我添加了一個淺層嵌套路線,並且所有內容都似乎正常工作。感謝您的幫助@moveson –