2017-09-01 79 views
0

使用嵌套的路由和關聯。我有一個創建租戶的部分,但在創建之後,它會保留呈現的表單並且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

回答

0

你呈現近你的問題的最終途徑:

tenant GET /tenants/:id(.:format)      tenants#show 

是不是租戶指數;這是個人租戶/展示路線。你可以這樣說,因爲它包含:id,這意味着它會向你顯示具有該ID的特定租戶。

嘗試再次運行rake routes。該指數的路線應該是這樣的:

tenants GET /tenants(.:format)      tenants#index 

如果你想創建或更新承租人記錄後返回給住戶索引,那麼你需要指定你TenantsController該路徑。在這兩個#create#update行動,您的重定向線(if @tenant.saveif @tenant.update後,分別)應改爲:

redirect_to tenants_path 

這將帶你到TenantsController,#INDEX行動。

在備選方案中,如果你想返回到各個租戶展示頁面,然後改爲在兩個#create#update行動來改變這兩個重定向在TenantsController:

redirect_to tenant_path(@tenant) 

這將帶你TenantsController,當前@tenant的#show動作。

+0

我最終改變了一些東西。我認爲我的主要問題是路由。我添加了一個淺層嵌套路線,並且所有內容都似乎正常工作。感謝您的幫助@moveson –

相關問題