ruby-on-rails - 从 Rails 4 中的另一个 Controller 呈现操作模板

标签 ruby-on-rails ruby-on-rails-4

我正在尝试在post/show View 中呈现replies/new View 。当我尝试

render "replies/new" 

它向我显示错误,因为它似乎在寻找

replies/_new.html.erb

当我用的时候它起作用了

render template: "replies/new"

但看起来它不会在回复 Controller 中激活新操作,因此它不会创建新回复。我可以在 Post show 操作中添加类似 @reply = Reply.new 的东西,但我认为必须有一些更干的方法来解决它。

最佳答案

But looks like it does not activate new action in replies controller so it doesn't create new reply

原因:- 渲染不创建新的 HTTP 请求(渲染不加载与 Controller 操作关联的任何上下文。因此,它将渲染模板),您可能在该新操作中有很多代码,但没有它将运行。只有 View 会被渲染。

你可以试试这个

posts#show

def show
  #foo = bar
  render "replies/new", locals: {reply: Reply.new}
end

以这种方式,您也必须在 replies#new 中使用局部变量

def new
  #foo = bar
  reply = Reply.new
  render locals: {reply: reply}
end

replies/new.html.erb 中使用 reply 而不是 @reply

关于ruby-on-rails - 从 Rails 4 中的另一个 Controller 呈现操作模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839273/

相关文章:

ruby-on-rails - 除了在一个字段上,我如何禁止更新?

ruby-on-rails - 是什么 !!和 Ruby 中的其他一些东西?

ruby-on-rails - 在 Rails 中,你可以设置 flash[ :error] when calling link_to?

css - Ruby on Rails - 博客网站上的按钮位置 - SASS

ruby-on-rails - View 片段中的俄罗斯套娃缓存和基于权限的链接

HTML/CSS 在我的 Rails 4 应用程序中表现得很奇怪(高度不可定制等)

ruby-on-rails - rails : RESTful resources: Worth using or inflexible/overrated?

ruby-on-rails - Rails 3 - 嵌套表单和默认值

javascript - 为什么 jQuery $(document).ready() 在验证失败后没有在 Rails 渲染 View 中触发?

ruby-on-rails - 如何在rails中为options_from_collection_for_select添加数据属性