我有两个型号Content和ContentType.在内容模型中,我可以这样做:
def get_all_content_except_poking_message
Content.all.where(:name.ne => "no forking, just poking")
end
Run Code Online (Sandbox Code Playgroud)
现在,我正在尝试在ContentType上应用范围.在内容模型中再次:
# Associations
belongs_to :content_type
def get_all_content_except_certain_content_type(content_type)
Content.all.where(:content_type.name.ne => content_type)
end
Run Code Online (Sandbox Code Playgroud)
但错误表明它在关联字段上应用范围的语法错误.
在模型中的关联字段上应用范围的正确方法是什么?
我也在使用has_scope gem.我也可以在控制器中应用相同的过滤器吗?就像是:
@contents = apply_scopes(
if params[:type]
@content_type = ContentType.find_by_slug(params[:type])
@content_type.contents.all
else
Content.all.where (:content_type.name.ne => "blogs")
end
)
Run Code Online (Sandbox Code Playgroud)
为了澄清,这里是irb输出:
irb(main):020:0> ContentType.all(:name=>"blogs").count
=> 1
irb(main):023:0> Content.last.content_type.name
=> "blogs"
irb(main):024:0> Content.all.where(:content_type => {:name => {'$ne' => "blogs"}}).count
=> 0
irb(main):026:0> Content.all.count
=> 4
Run Code Online (Sandbox Code Playgroud) model-view-controller ruby-on-rails mongodb mongoid has-scope
我创建了一个范围并将其指向数组类型。
has_scope: by_industry,: type =>: array
Run Code Online (Sandbox Code Playgroud)
现在我想让这个范围发挥作用。
我尝试像这样在 url 中传递参数:
http://localhost:3000/v1/find_friends?by_industry=[1,2]
Run Code Online (Sandbox Code Playgroud)
不起作用。
当范围是数组类型时,如何在url中正确写入参数?
我有一个事件模型,它有两个命名范围:
class Event < ActiveRecord::Base
scope :future, lambda { where('events.date >= ?', Time.zone.now) }
scope :past, lambda { where('events.date <= ?', Time.zone.now) }
end
Run Code Online (Sandbox Code Playgroud)
我通过创建两个新的控制器动作(名为"future"和"past")从我的控制器调用这些范围:
我的控制器:
class EventsController < InheritedResources::Base
actions :index, :show, :future, :past
has_scope :future
has_scope :past
def future
index! { @events = Event.future }
end
def past
index! { @events = Event.past }
end
end
Run Code Online (Sandbox Code Playgroud)
我还有这些额外行动的观点和路线.
这很好用.我的应用程序执行我想要的操作,并且可以链接到我的侧边栏中的新操作,如下所示:
%li
= link_to 'Events Home', events_path
%li
= link_to 'Future Events', future_events_path
%li
= link_to 'Past Events' past_events_path
Run Code Online (Sandbox Code Playgroud)
现在我对这个设置的问题是,虽然它工作得很好,但我不喜欢我必须为这些额外范围创建新的动作,视图和路由这一事实.我不认为我这样做是正确的.基本上我正在尝试过滤索引页面上的结果,但我必须创建新的操作,路由和视图来执行此操作.这看起来有点麻烦,我想知道是否有另一种方式.
如果我可以取消"未来"和"过去"控制器操作并且只是从视图中调用范围,那将是很好的: …
这是我的关注文件:controllerconcerns.rb
require 'active_support/concern'
module Query_scopes
extend ActiveSupport::Concern
has_scope :title
end
Run Code Online (Sandbox Code Playgroud)
这是我的控制器,我希望将其包含在:api_controller.rb中
class ApiController < ApplicationController
require 'concerns/controllerconcerns'
include Query_scopes
etc etc etc
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
undefined method `has_scope' for Query_scopes:Module
Run Code Online (Sandbox Code Playgroud)
我安装了has_scope gem,如果我只是'has_scope: scopename'在每个单独的控制器中说我希望它应用于它,它工作正常...那么如何在我的所有控制器中应用几行'has_scope'代码?