【问题标题】:Rails render template or partial but executing controllerRails 渲染模板或部分但正在执行的控制器
【发布时间】:2014-01-14 19:30:02
【问题描述】:

我正在尝试在对话框中显示信息。我希望从视图(模板)中加载此类信息。问题是,当我使用时

<%= render template:'panels/product_specifications' %>

它会尝试加载信息,但是由于我在视图中使用了控制器中定义的全局变量,并且控制器没有被执行,所以它抛出了我:

undefined method `banner_image_with_arrows_filename' for nil:NilClass

Extracted source (around line #2):

1: 
2: - banner_image = "banners/panels/#{@panel.banner_image_with_arrows_filename}"
3: #image-info
4:   %table
5:     %tr

@panel 变量在控制器中定义:

def load_panel
    @panel = Panel.find_or_build_from_id(params[:id])
    if !@panel.available_in_market?(market)
      add_flash_notice(t("pages.panel.text.not_available_in_market", :market => market.name), true)
    end
end

before_filter

我也尝试过render partial:'panels/products_specifications(首先使用下划线'product_specifications.html.erb'),render action:'panels/product_specifications', controller:'product_specifications 有不同的错误。

如何在执行控制器的情况下从另一个加载部分视图或视图?

编辑:

为了给你一个大图景,我想做的是向用户(当他将鼠标移到链接上时)显示一个对话框,其中预览了他点击该链接时将看到的内容。

【问题讨论】:

  • 你在哪里打电话render_to_string?在视图中?
  • render partial:'panels\products_specifications 这是正确的道路吗?应该是render partial: 'panels/products_specifications'
  • @polarblau:抱歉,当我发布问题时,我一定很困。我只用 renderrender partial: 'panels/products_specifications' 更正了 ir,因为我在代码中就是这样做的

标签: ruby-on-rails templates views partials


【解决方案1】:

如果我也理解,您点击了一个使用 before_filter 执行方法 load_panel 的操作,并且关联的视图,您正在尝试使用该变量呈现模板。

您应该尝试的第一件事是查看是否有Panel.find_or_build_from_id(params[:id]) 返回的记录。您可以使用puts 方法或使用像pry 这样的调试器。

您也可以尝试这样做&lt;%= render template:'panels/product_specifications', panel: @panel %&gt; 并使用panel 作为模板中的局部变量,如下所示:banners/panels/#{panel.banner_image_with_arrows_filename}

我认为最佳做法是使用presenter


聊天后的最终答案

您必须使用 ajax 来显示新面板并点击控制器操作。你可以看一个例子here

【讨论】:

  • 它永远不会到达控制器。我在控制台中放置了一个debugger 断点和一个puts "------------------------",但它永远不会到达那里。我不知道render 是否没有使用控制器,。我不能使用&lt;%= render template:'panels/product_specifications', panel: @panel %&gt;,因为页面中没有定义@panel 我有链接会在点击时显示对话框
  • 渲染不会命中控制器方法。您必须使用演示者或在与路由一起使用的控制器操作上创建变量。
  • 它不是控制器方法,是动作。也许我误解了一些东西。这是我的控制器,查看和路由fpaste.org/64549。什么是演示者?
  • 如果我理解的话,主要问题是动作product_specifications 永远不会被触发。尝试用这个get '/panels/product_specifications' 替换您的路线(在开头添加/)。
猜你喜欢
  • 1970-01-01
  • 2012-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
相关资源
最近更新 更多