首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将has_scopes gem中的current_scopes作为参数传递

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

Stack Overflow用户
提问于 2015-02-19 08:32:37
回答 1查看 690关注 0票数 3

这个问题我已经纠结了好几天了。我是一名律师,我正在建立一个问答类型的法律咨询网站(yups,我是rails的新手:-)。

我希望用户能够过滤问题的类别(即公司法,知识产权等),然后能够排序他们在次要的基础上,最近或流行等。

我尝试了许多方法,但最终,在尝试按最近、流行等排序时,我找不到一种方法来传递被选为另一个参数的当前类别。

我刚刚开始使用作用域gem,我从文档中看到有一个名为‘has_scopes _scopes’的方法。我似乎想不出如何在视图中将current_scopes作为参数传递,这样就可以调用最近的或流行的作用域。从逻辑上讲,我假设current_scopes需要被赋值给控制器中的一个变量,但是同样,无法确定如何将其作为参数传递到视图中。

我当前的代码:

post.rb

代码语言:javascript
复制
    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

代码语言:javascript
复制
  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

代码语言:javascript
复制
    <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>

谢谢你,真的很感谢你在这件事上的帮助。

EN

回答 1

Stack Overflow用户

发布于 2019-04-03 05:09:04

对于其他正在寻找此问题答案的人来说,只有在调用apply_scopes之后,current_scopes值才可用。此问题已记录在here中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28596676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档