简体   繁体   English

Rails-在控制器中,如何从其他控制器渲染动作?

[英]Rails - in controller, how to render an action from a different controller?

I have a page where is displayed information about a respective car (it's a controller cars , action show ). 我有一个页面,在该页面上显示有关相应汽车的信息(这是控制器cars ,动作show )。 On this page, I render _form from the controller called reviews . 在此页面上,我从名为reviews的控制器渲染_form

When I send out the form (through AJAX), the review is successfully created, but I am not able from the reviews controller render any action from the cars controller - to be more specific, here's the code: 当我发送表格(通过AJAX)时,评论已成功创建,但是我无法从reviews控制器中渲染cars控制器的任何操作-更具体地说,这是代码:

# reviews_controller
  def create
    @review = Review.new(review_params)
    @review.save
    #respond_with(@review)
    respond_to do |format|
      format.js { render :action => "/cars/car_profile" }
    end
  end

The error I get: 我得到的错误:

ActionView::MissingTemplate (Missing template reviews/cars/car_profile, application/cars/car_profile with {:locale=>[:en], :formats=>[:js, :html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml, :jbuilder]}. Searched in:
  * "/Users/adam/rubydev/claisy/app/views"
  * "/Users/adam/.rvm/gems/ruby-2.0.0-p481/gems/devise-3.4.1/app/views"
):
  app/controllers/reviews_controller.rb:28:in `block (2 levels) in create'
  app/controllers/reviews_controller.rb:27:in `create'

How can I render in controller an action that is located in a different controller? 如何在控制器中渲染位于其他控制器中的动作?

Thank you in advance. 先感谢您。

:action forces rails to search for templates within the current controller view folder. :action强制rails在当前控制器视图文件夹中搜索模板。

Missing template reviews/cars/car_profile 缺少模板评论/汽车/ car_profile

You should write this instead 你应该写这个

render "cars/car_profile"

See point 2.2.3 2.2.3点

What if you want to render a template from an entirely different controller from the one that contains the action code? 如果要从与包含动作代码的控制器完全不同的控制器渲染模板,该怎么办? You can also do that with render, which accepts the full path (relative to app/views) of the template to render. 您也可以使用render来做到这一点,后者接受要渲染的模板的完整路径(相对于应用程序/视图)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM