Rails: method chaining in model

天大地大妈咪最大 提交于 2019-12-11 05:08:33

问题


Trying to create a search method in my model and join conditions based on arguments passed to the method. However, nothing gets chained after the initial "where"

Controller:

Item.search(args)

Model:

  def self.search(args = {})
    include ActsAsTaggableOn # Tagging model for search

    result = where("title LIKE ? OR description LIKE ? OR tags.name LIKE ?", "%#{args[:search]}%", "%#{args[:search]}%", "%#{args[:search]}%")
      .joins("JOIN taggings ON taggings.taggable_id = items.id")
      .joins("JOIN tags ON taggings.tag_id = tags.id")

      # Categories
      if args[:categories]
        result.where(:category_id => args[:categories])
      end

      # Order
      if args[:order] == "category"
       result.joins(:categories).order("categories.title ASC")
      else
        result.order("title DESC")
      end


      # Pagination
      result.paginate(:per_page => 10, :page => args[:page])

end

Even if I strip out the if block and do a chain directly afterwards, it doesn't work:

result = where(:foo => "bar")
result.order("name DESC")

... runs just the where.

Any ideas?

Thank in advance.


回答1:


What you should do is chain it by adjusting the definition of result as you go:

result = result.where(...)

Each time you must re-assign back to result with the updated scope. This is because result.where returns a new scope, it does not adjust the existing scope.



来源:https://stackoverflow.com/questions/4963045/rails-method-chaining-in-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!