是否可以通过传递集合的局部变量来呈现局部视图?

时间:2019-01-03 16:45:13

标签: ruby-on-rails

在Rails 5.2.2中,我试图使用局部变量作为集合来渲染部分,但是在对Map视图进行测试时,我在部分中得到了错误:

// Your Topic Resource
ConfigResource cr = new ConfigResource(Type.TOPIC, "mytopic");

// Create all your configurations
Collection<ConfigEntry> entries = new ArrayList<>();
entries.add(new ConfigEntry(TopicConfig.SEGMENT_BYTES_CONFIG, String.valueOf(segmentbytes)));
entries.add(new ConfigEntry(TopicConfig.RETENTION_BYTES_CONFIG, String.valueOf(retentionBytes)));
...

// Create the Map
Config config = new Config(entries);
Map<ConfigResource, Config> configs = new HashMap<>();
configs.put(cr, config);

// Call alterConfigs()
admin.alterConfigs(configs);

work_centers_controller.rb

get

kanban.html.erb

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>'

_item_kanban.html.erb

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

在其他视图中,我使用集合实例变量(例如<% @wc_items.each do |wc, items| %> <%= render partial: 'item_kanban', collection: items %> <% end %> )渲染部分,并引用部分中的单数变量(例如<%= link_to item, class: "list-group-item" do %> <%= item.number %> <% end %> )。我希望这个局部变量使用本地集合变量的行为相同。

1 个答案:

答案 0 :(得分:0)

请尝试

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

现在您可以访问

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

当你这样做

<%= render partial: 'item_kanban', collection: items %>将为您提供item_kanban局部变量,而不是item变量。

因此,您需要通过as: :item指定它,现在您可以访问item