Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 是否可以仅使用命名作用域重写此查询?_Ruby On Rails_Ruby On Rails 4.1 - Fatal编程技术网

Ruby on rails 是否可以仅使用命名作用域重写此查询?

Ruby on rails 是否可以仅使用命名作用域重写此查询?,ruby-on-rails,ruby-on-rails-4.1,Ruby On Rails,Ruby On Rails 4.1,我希望只使用命名范围编写此查询。原因很简单,当我改变客户端被视为活动的方式时,我不想到处更改代码(对于用户被视为可连接的也一样) 这是我的密码 客户端.rb class Client < ActiveRecord::Base has_one :user scope :actives, -> { where(starting_date: a_date, finishing_date: another_date, enabled: true) } end class User

我希望只使用命名范围编写此查询。原因很简单,当我改变
客户端被视为活动的方式时,我不想到处更改代码(对于
用户
被视为可连接的也一样)

这是我的密码

客户端.rb

class Client < ActiveRecord::Base
  has_one :user

  scope :actives, -> { where(starting_date: a_date, finishing_date: another_date, enabled: true) }
end
class User < ActiveRecord::Base
  belongs_to :client

  scope :connectable, -> { where.not(access_token: nil, instance_url: nil) }
end

和一个指向的链接以供参考

我不确定这是一个多么好的主意,但只要您确保列名的名称间隔正确(即,如果不在表名前加前缀,客户端和用户中都不能有“foo”),那么这应该可以工作:

User.eager\u load(:client.connectable.where(client.active.where\u values.map(&:to\u sql.join(“AND”))

一定有更好的方法,但上面的方法对我很有效:

课程模式:

scope :valid, -> { enabled.has_country }
scope :has_country, -> { where.not(country_id:nil) }
Rails控制台:

> Course.where(Course.valid.where_values.map(&:to_sql).join(" AND ")).to_sql
=> "SELECT \"courses\".* FROM \"courses\"  
    WHERE (\"courses\".\"is_enabled\" = 't' 
    AND \"courses\".\"country_id\" IS NOT NULL)"

你要找的是阿雷尔的
merge
方法。()

试试这个:

User.connectable.includes(:client).merge(Client.actives).references(:clients)

包含(:client)
将从用户引入:client关系,这将使
合并(client…
范围工作。Rails 4+需要
.references
来明确说明
includes
语句将引用哪个表。

mhh,这对meGood来说太麻烦了,我尝试了
合并
,但没有考虑到我必须在Rails 4中使用includes(或
渴望加载
)而新的
引用了
东西。谢谢,我会用这个更新我的代码。
User.connectable.includes(:client).merge(Client.actives).references(:clients)