【问题标题】:How to render view from of a different controller?如何从不同的控制器渲染视图?
【发布时间】:2014-03-27 04:22:19
【问题描述】:

在我的项目中,我有两个控制器,分别称为 PropertiesControllerFacilitiesController。在PropertiesController 中创建property 后,我想从FacilitiesController 加载view(form)

我尝试使用 render facilities/new 显示错误(表单中的第一个参数不能包含 nil 或为空),因为我尚未初始化传递给 form_for 方法的参数(@facility)。

我可以通过初始化PropertiesController 中的@facility 变量来避免上述错误。但我在form_for 中有代码,它调用FacilitiesController 中的object 上的方法。我不希望所有代码在PropertiesController 中再次重复。

如何在不复制代码的情况下从FacilitiesController 渲染视图?

【问题讨论】:

  • 这意味着在创建属性后您要查看设施表单。对吗?
  • 是的,我想从设施控制器加载视图。
  • 在创建属性之后,您可以重定向到设施新方法,它呈现设施的形式。
  • 是的,我可以使用 redirect_to 控制器重定向:'facilities',操作:'new'

标签: ruby-on-rails forms controller


【解决方案1】:

希望下面的代码对你有用

class PropertiesController < ApplicationController


 def create
  @property = Property.new(property_params)

  respond_to do |format|
   if @property.save
     format.html { redirect_to facility_new_path, notice: 'Property was successfully created.' }
   else
    format.html { render action: 'new' }
    format.json { render json: @property.errors, status: :unprocessable_entity }
   end
  end
 end

end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    相关资源
    最近更新 更多