【问题标题】:Is it possible to render a partial by passing a local variable for the collection?是否可以通过为集合传递局部变量来呈现部分?
【发布时间】:2019-05-30 06:54:58
【问题描述】:

在 Rails 5.2.2 中,我尝试使用局部变量作为集合来呈现部分,但是在对 get 运行测试时,视图中出现了部分错误:

ActionView::Template::Error:         ActionView::Template::Error: undefined local variable or method `item' for #<#<Class:0x00000007503de8>:0x000000093f2240>
        app/views/work_centers/_item_kanban.html.erb:1:in `_app_views_work_centers__item_kanban_html_erb__413475955005549970_77587680'
        app/views/work_centers/kanban.html.erb:5:in `block in _app_views_work_centers_kanban_html_erb__2029427675221229249_77567000'
        app/views/work_centers/kanban.html.erb:4:in `each'
        app/views/work_centers/kanban.html.erb:4:in `_app_views_work_centers_kanban_html_erb__2029427675221229249_77567000'
        test/controllers/work_centers_controller_test.rb:27:in `block in <class:WorkCentersControllerTest>'

work_centers_controller.rb

def kanban
  # Get hash of form {"Laser"=>["Item1", "Item2"], "Brake"=>["Item2"]}
  @wc_items = HashWithIndifferentAccess.new
  WorkCenter.all.each do |wc| 
    @wc_items[wc.name] = Item.where('id IN (SELECT item_id 
                                            FROM routings 
                                            WHERE work_center_id = ?)', wc.id) 
                             .where('id NOT IN (SELECT item_id 
                                                FROM status_updates 
                                                WHERE work_center_id = ?)', wc.id) 
                             .pluck(:number)
  end
end

看板.html.erb

<% @wc_items.each do |wc, items| %>
  <%= render partial: 'item_kanban', collection: items %>
<% end %>

_item_kanban.html.erb

<%= link_to item, class: "list-group-item" do %>
  <%= item.number %>
<% end %>

在其他视图中,我使用集合实例变量(例如@items)呈现部分,并在部分中引用奇异变量(例如item)。我希望这部分使用本地集合变量的行为方式相同。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    请尝试一下

    <%= render partial: 'item_kanban', collection: items, as: :item %>
    

    现在你可以访问了

    <%= link_to item, class: "list-group-item" do %>
      <%= item.number %>
    <% end %>
    

    什么时候做的

    &lt;%= render partial: 'item_kanban', collection: items %&gt; 会给你一个item_kanban 局部变量,而不是item 变量。

    所以你需要通过as: :item指定它现在你可以访问item

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多