相关疑难解决方法(0)

ActiveRecord OR查询哈希表示法

我知道有三个主要的符号为whereActiveRecord方法提供参数:

  1. 纯字符串
  2. 排列
  3. 哈希

指定andwhere方法是直截了当:

# Pure String notation
Person.where("name = 'Neil' AND age = 27")

# Array notation
Person.where(["name = ? AND age = ?", 'Neil', 27])

# Hash notation
Person.where({name: "Neil", age: 27})
Run Code Online (Sandbox Code Playgroud)

or为这个相同的where方法指定是为了哈希语法.可能吗?

# Pure String notation
Person.where("name = 'Neil' OR age = 27")

# Array notation
Person.where(["name = ? OR age = ?", 'Neil', 27])

# Hash notation DOESN'T WORK
Person.where({name: "Neil" OR age: 27})
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails ruby-on-rails-4 rails-activerecord ruby-on-rails-5

72
推荐指数
1
解决办法
2万
查看次数

Rails 4语法 - 多个条件

我该怎么写这个呢?

Request.pending.where(.....)  ## Request.pending = request.state_id in (1..3)
Run Code Online (Sandbox Code Playgroud)

这些是条件:

approver1_id = current_user and state_id = 1
or
approver2_id = current_user and state_id = 2
or
approver3_id = current_user and state_id = 3
Run Code Online (Sandbox Code Playgroud)

如果我可以将这些条件放在模型中以便在其他控制器/视图中使用,那将是非常好的,因为我将在整个应用程序中经常使用这些条件.

ruby-on-rails

6
推荐指数
2
解决办法
2万
查看次数

Rails结合了多个activerecord关系

我想结合多个活动记录关系

例如,

apple_companies = Company.where("name like ?","%apple%")
banana_companies = Company.where("name like ?","%banana%")
Run Code Online (Sandbox Code Playgroud)

我想结合这两种关系.

不合并,合并是apple_companies.merge(banana_companies)=> Company.where("名称像?和名字一样?","%apple%","%banana%")

我想要Company.where("名字喜欢?或名字喜欢?","%apple%","%banana%")

之后,

我会编码

companies = Company.none
company_name_list.each do |name|
    like = "%"+name+"%"
    companies += Company.where("name like ?",like)
end
Run Code Online (Sandbox Code Playgroud)

但是我写的代码使公司成为阵列......

所以我不能订购和页面公司...... :(

谢谢

ruby ruby-on-rails-4 rails-activerecord activerecord-relation

5
推荐指数
3
解决办法
8084
查看次数

在范围中使用OR与查询

在Rails3中我有:

Class Teacher
  #  active                 :boolean
  has_and_belongs_to_many :subjects

Class Subject
  #  active                 :boolean
  has_and_belongs_to_many :teachers
Run Code Online (Sandbox Code Playgroud)

我正在尝试构建一个教师范围,它返回与之相关的所有Teachers内容active或与之相关联的Subject内容active.

这些范围单独工作,但如何将它们作为单个范围与OR组合?

scope :active_teachers, where(active: true)
scope :more_active_teachers, joins(:subjects).where(:subjects => {active: true})
Run Code Online (Sandbox Code Playgroud)

我试过这个没有成功:

scope :active_teachers, where(active: true).or(joins(:subjects)
      .where(:subjects => {active: true}))
Run Code Online (Sandbox Code Playgroud)

更新:

我以为我有一个解决方案,但这不再是懒惰的负载,两次点击数据库 - 最重要的是 - 返回一个数组而不是一个AR对象!

scope :active_teachers, where(active: true) |
                        joins(:subjects).where(:subjects => {active: true})
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails ruby-on-rails-3

2
推荐指数
1
解决办法
1133
查看次数