Rails 4 params没有被发送到控制器

时间:2015-02-04 20:14:24

标签: ruby-on-rails params

我一直在努力争取成为某人的快速答案......

我有嵌套部分的视图。该索引具有部分属于子类别的类别。

类别按预期循环,但由于某种原因,本地人似乎没有到达控制器。

我的代码如下:

index.html.erb

<%= render partial: "categories/categories", object: @categories %>

_categories.html.erb

    <% @categories.each do |category| %>
        <% if category.category_parent == 0 %>
            <li><a href=""><%= category.category_name %> <i class="icons icon-right-dir"></i></a>
                <%= render partial: "categories/subcategories", object: @subcategories, locals: {parent_id: category.category_id} %>
            </li>
        <% end %>
    <% end %>

_subcategories.html.erb

      <% if @parent != nil %>
      <ul class="sidebar-dropdown">
        <li>
          <ul>
            <% @subcategories.each do |subcategory| %>
              <li><a href=""><%= subcategory.category_name %> <i class="icons icon-right-dir"></i></a></li>
            <% end %>
          </ul>
        </li>
      </ul>
      <% end %>

categories_controller.rb

class CategoriesController < ApplicationController
  before_action :categories, :subcategories

  def categories
    @categories = Category.all
  end

  def subcategories
    @parent = params[:parent_id]
    @subcategories = Category.where(:category_parent => params[:parent_id])
  end

end

1 个答案:

答案 0 :(得分:0)

@categories是一个实例变量,您不需要将它从视图传递到视图。所以第一个渲染语句变为:

<%= render "categories/categories" %>

(离开partial:时我更熟悉)

_categories.html.erb 变为:

<% @categories.each do |category| %>
  <% if category.category_parent == 0 %>
    <li><a href=""><%= category.category_name %> <i class="icons icon-right-dir"></i></a>
      <%= render "categories/subcategories", category: category %>
      <%# Note passing in category to have access to it as a local %>
    </li>
  <% end %>
<% end %>

_subcategories.html.erb

<% if category != nil %>
  <ul class="sidebar-dropdown">
    <li>
      <ul>
        <% category.subcategories.each do |subcategory| %>
          <li><a href=""><%= subcategory.category_name %> <i class="icons icon-right-dir"></i></a></li>
        <% end %>
      </ul>
    </li>
  </ul>
<% end %>

我认为您不应该在控制器中查找@subcategories。看起来在def categories中您只是获取所有类别,然后在视图中循环遍历它们。实际上,这将是n + 1,因为每次它循环一个新类别时,它将不得不进行数据库查询以查找其子类别。你可以用include来避免这种情况。

<强> categories_contorller.rb

def categories
  @categories = Category.all.includes(:subcategories)
end

这是我认为最简单和最清晰的。但我也没有过多地使用object:。如果你想坚持这种模式,这post可能对你有所帮助: