我用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的查询界面做类似的事情?
我知道有三个主要的符号为where
ActiveRecord方法提供参数:
指定and
的where
方法是直截了当:
# 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
相对较新的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个外键一起使用,或者根据对象的性别更改外键?或者还有其他/更好的方式吗?
谢谢!
我正在使用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::Relation
以这样的方式得到两个对象的并集,结果应该是另一个活动的记录关系.我怎么能做到这一点?