相关疑难解决方法(0)

ActiveRecord查询联盟

我用Ruby on Rail的查询接口写了几个复杂的查询(至少对我来说):

watched_news_posts = Post.joins(:news => :watched).where(:watched => {:user_id => id})
watched_topic_posts = Post.joins(:post_topic_relationships => {:topic => :watched}).where(:watched => {:user_id => id})
Run Code Online (Sandbox Code Playgroud)

这两个查询都可以自行完成.两者都返回Post对象.我想将这些帖子合并到一个ActiveRelation中.由于某些时候可能有数十万个帖子,因此需要在数据库级别完成.如果是MySQL查询,我可以简单地使用UNION运算符.有没有人知道我是否可以用RoR的查询界面做类似的事情?

union activerecord ruby-on-rails active-relation

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

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模型has_many有多个foreign_keys

相对较新的rails并尝试使用具有name,gender,father_id和mother_id(2个父项)的单个Person模型来建模一个非常简单的族"树".下面基本上是我想要做的,但显然我不能重复:has_many中的孩子(第一个被覆盖).

class Person < ActiveRecord::Base
  belongs_to :father, :class_name => 'Person'
  belongs_to :mother, :class_name => 'Person'
  has_many :children, :class_name => 'Person', :foreign_key => 'mother_id'
  has_many :children, :class_name => 'Person', :foreign_key => 'father_id'
end
Run Code Online (Sandbox Code Playgroud)

是否有一种简单的方法可以将has_many与2个外键一起使用,或者根据对象的性别更改外键?或者还有其他/更好的方式吗?

谢谢!

ruby model ruby-on-rails has-many

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

为什么Rails模型关联结果不是自然的ActiveRecord :: Relations?

我正在使用Rails 3.2.0

比方说我有:

class Comment < ActiveRecord::Base
  has_many :articles
end

c1 = Comment.last
Run Code Online (Sandbox Code Playgroud)

然后

c1.articles.class
# => Array

c1.articles.where('id NOT IN (999999)').class
# => ActiveRecord::Relation    
Run Code Online (Sandbox Code Playgroud)

为什么关联的结果不是一种类型ActiveRecord::Relation

它显然是/ 在某个时候:

c1.articles.to_orig
# undefined method `to_orig' for #<ActiveRecord::Relation:0x007fd820cc80a8>

c1.articles.class
# => Array
Run Code Online (Sandbox Code Playgroud)

某些评估作用于ActiveRecord :: Relation对象,但检查该类会给出不同的类型.


特别是,当merge用于连接多个查询时,这会破坏构建延迟加载的查询.

activerecord types lazy-loading ruby-on-rails

12
推荐指数
1
解决办法
3127
查看次数

添加两个ActiveRecord :: Relation对象

你如何将两个关系加在一起?当我尝试+运算符时,它返回一个数组.但我需要它来回归关系.

谢谢,迈克

ruby ruby-on-rails-3

9
推荐指数
1
解决办法
7268
查看次数

两个活跃记录关系的联盟应该是ruby on rails的另一个活跃记录

我需要ActiveRecord::Relation以这样的方式得到两个对象的并集,结果应该是另一个活动的记录关系.我怎么能做到这一点?

activerecord ruby-on-rails

7
推荐指数
1
解决办法
8523
查看次数