2017-09-01 77 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 –

相关问题