【发布时间】:2017-09-01 06:31:05
【问题描述】:
使用嵌套路由和关联。我有一个创建租户的部分,但在创建后它保留呈现的表单并且 url 更改为 /tenants。期望的行为是它需要重定向到显示页面。路线如下:
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
最后,rake 路由中的 show#tenants 是:
tenant GET /tenants/:id(.:format) tenants#show
我已广泛搜索此主题,但没有任何成功。任何帮助表示赞赏。导轨 5.1
【问题讨论】:
标签: ruby-on-rails ruby forms activerecord associations