将has_scopes gem中的current_scopes作为参数传递

问题描述 投票:3回答:1

几天来我一直在努力解决这个问题。我是一名律师,我正在建立一个Q&A类型的网站以获取法律建议(是的,我是铁路的相对新手:-))。

我希望用户能够按类别(即公司法,IP等)过滤问题,然后能够在次要基础上按最近或最受欢迎等方式对其进行排序。

我已经尝试了很多方法,最终,在尝试按最近,流行等排序时,我一直无法找到将当前类别作为另一个参数传递的方法。

我刚刚开始使用has_scopes gem,我从文档中看到有一个名为'current_scopes'的方法。我似乎无法弄清楚如何在视图中传递current_scopes作为一个参数,然后可以在其上调用最近或流行的范围。从逻辑上讲,我假设需要将current_scopes分配给控制器中的变量,但是再次无法确定如何在视图中将其作为参数传递。

我目前的代码:

post.rb

    has_many :comments, dependent: :destroy
    belongs_to :user, :counter_cache => true
    belongs_to :category, :counter_cache => true

    scope :recent,      ->{ order("created_at DESC")}
    scope :popular,     -> { order("comments_count DESC")}
    scope :unanswered,  -> {where(comments_count: 0)}
    scope :category, -> category_id {where(:category_id => category_id)}

posts_controller.rb

  has_scope :category 
  has_scope :recent, :type => :boolean
  has_scope :popular, :type => :boolean
  has_scope :unanswered, :type => :boolean

  def index
    @posts = @q.result.includes(:comments).order("created_at DESC") #@q comes from using Ransack gem and applying in the application controller
    @posts = apply_scopes(Post).all
    @scope = current_scopes

_sidebar.html.erb

    <h3>Filter by: </h3>
     <ul class="side-nav fixed" role="navigation" title="Link List">
       <li role="menuitem"><%= link_to "Show all", root_path %></li>
       <li role="menuitem"><%= link_to "Corporate", category: 1 %></li>
       <li role="menuitem"><%= link_to "Intellectual Property", category: 2 %></li>
       <li role="menuitem"><%= link_to "Employment", category: 3 %></li>
       <li role="menuitem"><%= link_to "Commercial", category: 4 %></li>
       <li role="menuitem"><%= link_to "Real Estate", category: 5 %></li>
       <li role="menuitem"><%= link_to "Venture Capital", category: 6 %></li>
     </ul>

    <h3>Sort by:</h3>
      <li> <%= link_to "Most Recent", :recent => true %> </li>
      <li> <%= link_to "Most Popular", :popular => true  %></li>
      <li> <%= link_to "Unanswered", :unanswered => true %></li>

谢谢,非常感谢您对此事的任何帮助。

ruby-on-rails ruby rails-activerecord scopes has-scope
1个回答
0
投票

对于寻找这个问题答案的其他人来说,current_scopes值仅在调用apply_scopes后才可用。问题记录在here

© www.soinside.com 2019 - 2024. All rights reserved.