【问题标题】:Passing current_scopes from the has_scopes gem as a param将 has_scopes gem 中的 current_scopes 作为参数传递
【发布时间】:2015-04-20 05:24:15
【问题描述】:

我已经为这个问题苦苦挣扎了好几天。我是一名律师,我正在建立一个问答类型的网站以获取法律建议(是的,我是 Rails 的新手 :-))。

我希望用户能够按类别(即公司法、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>

谢谢您,非常感谢您在此问题上提供的任何帮助。

【问题讨论】:

  • 我不喜欢在控制器中使用第三方库:控制器的行为通常非常具体,您最终会花费太多时间来尝试了解问题所在并根据自己的需要调整功能(设计,我恨你胜过爱你)。您是否已经与has_scope 耦合,或者您可以摆脱它?
  • 嗨,根本没有耦合到 has_scopes。这是我在努力 1(仅使用范围)和努力 2(使用单独的类别和过滤器模型)失败后的第三个策略。所以基本上,很高兴摆脱它,如果它有助于解决问题! :-)
  • 很好,谢谢!!!

标签: ruby-on-rails ruby rails-activerecord scopes has-scope


【解决方案1】:

对于寻找此问题答案的其他人,current_scopes 值仅在调用 apply_scopes 后可用。该问题记录在here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-26
    • 2020-09-18
    • 2015-05-24
    • 2012-11-10
    • 2020-10-30
    • 2014-02-25
    • 1970-01-01
    相关资源
    最近更新 更多