【问题标题】:Getting 'form_for(@something)' to work outside of new.html.erb让“form_for(@something)”在 new.html.erb 之外工作
【发布时间】:2013-06-21 19:20:21
【问题描述】:

我想将我当前位于 app/views/something/new.html 中的 <%= form_for(@something) do |f| %> 放置在多个页面中,所以可能在 app/views/layouts/application.html.erb 中

如何让@something 变量和表单在那里或其他地方正常工作——因为它是在SomethingController 的控制器#new 操作中定义的,它似乎只在适当的@987654324 中可用@查看..

【问题讨论】:

  • 很确定这不是最佳实践,但您是否尝试过应用程序控制器?
  • 所以基本上你想在你的app/views/layout/application.html.erb 中输入一个表格,如果我的立场正确的话
  • 是的,但我的 SomethingController 中有“创建”操作..

标签: ruby-on-rails ruby ruby-on-rails-3.2 actionpack


【解决方案1】:

您可以将表单放在任何地方,只需在控制器中提供@something的实例变量

基本用法在这里。

ThisThingsController
  def show
    @this_thing = foo
    @that_thing  = bar
  end
end

# View
<%= @this_thing %>
<%= form_for @that_thing %>

当然你可以使用partial来渲染表单,只要你给它提供它需要的变量。

【讨论】:

    【解决方案2】:

    试试

    <%= form_for SomeThing.new do |f| %>
    

    【讨论】:

      【解决方案3】:

      在不完全了解您要完成的工作的情况下,我会提出这个建议。 在 ApplicationController 中添加一个前置过滤器(或者,您可以创建一个模块并在需要的地方混合它)。然后在需要时调用 before_filter。此示例将始终运行 before 过滤器:

      class ApplicationController
        before_filter :set_something
      
        private
        def set_something
          @something = ...  # Fill in the logic here
        end
      end
      

      然后在需要的地方添加您的表单。您甚至可以根据是否设置了@something 使其有条件地出现。

      <% if @something %>
        # Form goes here
      <% end %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-06
        • 1970-01-01
        相关资源
        最近更新 更多