Ruby on rails 如何通过列将ActiveRecord结果与select_all结果联接?
如何通过post_id列将c和p连接成一个表式结构 就像在SQL中一样:Ruby on rails 如何通过列将ActiveRecord结果与select_all结果联接?,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,如何通过post_id列将c和p连接成一个表式结构 就像在SQL中一样: class Author has_many :post end class Post belong_to :author has_many :content end class Content belong_to :post (column: section) end c = Content.select("post_id").where("section like ?", 'foo%')
class Author
has_many :post
end
class Post
belong_to :author
has_many :content
end
class Content
belong_to :post
(column: section)
end
c = Content.select("post_id").where("section like ?", 'foo%')
p = ActiveRecord::Base.connection.select_all(Post.select("title, post_id ").joins(:author).where(:id => c.map(&:post_id)).to_sql)
非常感谢。这段代码
select * from c,p where c.post_id = q.post_id ;
将根据需要生成SQL。您可以分别访问每个周期中每个帖子的内容,或生成类似DB returns的平面表,执行如下操作:
@posts = Content.find(:all, :include => :post)
NoMethodError:未定义的“合并”方法,有什么想法吗?谢谢。哦,对不起,我弄错了。这行不通,因为它不是散列,而是对象。您可以使用{:post\u id=>c.post.id、:content\u name=>c.name、:post\u name=>c.post.name}或任何您喜欢的内容替换例如c.mergec.post。更重要的是,Rails已经从DB中获得了所有必要的数据,您可以随意使用它们。我将'c.mergec.post'替换为{:post\u id=>c.post.id}。但是:post_id未定义。还在想办法。。。
@posts = Content.find(:all, :include => :post).map{|c| c.merge(c.post)}