Tag: join

Rails:如何选择没有特定相关(关联)对象的记录(SQL EXISTS简要操作方法)

假设我们有用户: class User < ActiveRecord::Base has_many :connections has_many :groups, through: :connections end 和团体: class Group < ActiveRecord::Base has_many :connections has_many :users, through: :connections end 基本上,标准的多对多连接: class Connection belongs_to :user belongs_to :group end 我打算做的是: 仅选择不属于给定的一组组的用户(具有ID的组[4,5,6] ) 仅选择属于一组( [1,2,3] )且不属于另一组( [4,5,6] )的用户 仅选择不属于组的用户 另外,我不想: 从数据库中获取大量数据以使用Ruby代码对其进行操作。 我知道在CPU和内存方面效率低下(Ruby比任何常用的数据库引擎慢得多,通常我想依靠数据库引擎来完成繁重的工作) 我尝试了像User.joins(:group).where(group_id: [1,2,3]).where.not(group_id: [4,5,6]) ,它们返回错误的结果(结果中的一些用户)集合属于组4,5,6 以及 1,2,3) 我不想仅仅为了检查存在而进行连接,因为我知道对于DB来说这是一个非常复杂的(即CPU /内存密集型)操作

使用带有连接的占位符

我试图通过在连接上替换我的参数来避免任何SQL注入漏洞。 Category.joins(“LEFT OUTER JOIN incomes ON incomes.category_id = categories.id AND incomes.dept_id = ?”, params[:Dept]) 这会尝试在其中执行带有问号的查询,而不是将其替换为param。 这样做的正确方法是什么? 编辑: 查询需要返回: SELECT categories.* FROM “categories” LEFT OUTER JOIN incomes ON incomes.category_id = categories.id AND incomes.dept_id = 86 不 SELECT categories.* FROM “categories” LEFT OUTER JOIN incomes ON incomes.category_id = categories.id WHERE incomes.dept_id = 86 结果非常不同!

rails:这个关联条件的多重连接有什么问题?

这是我的模特: class Deck < ActiveRecord::Base belongs_to :game has_many :deck_cards end class DeckCard < ActiveRecord::Base belongs_to :card belongs_to :deck end class Card < ActiveRecord::Base end 这是我试图找到的: DeckCard.all :joins => [:card, :deck], :conditions => {{:decks => {:game_id => @game.id}}, {:cards => {:present => true}}} 我一直收到错误:#Class的all未定义方法:0x4b2a98>。 我假设这是解析我的条件时的一个误导性错误。 我正在关注Active Record Query指南。 我不确定是否使用单数或复数forms的关联。 看起来像使用belongs_to,你应该在:join连接哈希中使用单数forms,但我不确定:条件哈希,所以我尝试了两者并且都没有工作。 如果不清楚,我在SQL中尝试做的是: SELECT * from DeckCards INNER […]

无法在Rails中加入自联接表

我有2个型号 class Category “Category” has_many :children, :class_name => “Category”, :foreign_key => “parent_id” has_many :products attr_accessible :description, :title, :parent end class Product < ActiveRecord::Base belongs_to :category end 特别是,类别有一个标题为“茶”的父项,这个项目有很多儿童项目:“红茶”,“白茶”…… 我需要选择属于父类“茶”的产品。 我是这样做的: Product.joins(:category=>:parent).where(:category=>{:parent=>{:id=>1}}).all 它抛出exception(无法格式化) Product Load (0.8ms) SELECT `products`.* FROM `products` INNER JOIN `categories` ON `categories`.`id` = `products`.`category_id` INNER JOIN `categories` `parents_categories` ON `parents_categories`.`id` = `categories`.`parent_id` WHERE `parent`.`id` […]

Rails – 按连接表数据排序

我在工作中有一个RoR项目。 以下是我的模型的适用部分。 家 has_many :communities, :through => :availabilities has_many :availabilities, :order => “price ASC” 社区 has_many :homes, :through => :availabilities has_many :availabilities 可用性 belongs_to :home belongs_to :community 数据库中的“可用性”表具有附加数据列“价格” 所以现在我可以打电话了 @home.availabilities.each do |a| a.community.name a.price 并按我的要求取回按价格订购的可用性数据。 我的问题是: 有没有办法通过avaliabilities.first.price (第一个=最低)自动订购Homes? 也许是default_scope :order东西default_scope :order ?