Ruby on rails 基于单个列强制关系的唯一性
我的使用者模型上有一个类方法,它作为作用域(作用于Ruby on rails 基于单个列强制关系的唯一性,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,我的使用者模型上有一个类方法,它作为作用域(作用于ActiveRecord::Relation,返回ActiveRecord::Relation,可以菊花链)并返回一些使用者的双倍值。我希望它只返回唯一的消费者,而我似乎找不到一种方法来使用Rails助手或正确的SQL来传递以获得我想要的。我觉得这里有一个简单的解决方案——这不是一个复杂的问题 我基本上想要Array#uniq,但是对于ActiveRecord::Relation。我尝试了一个select-DISTINCT语句 Consumer.
ActiveRecord::Relation
,返回ActiveRecord::Relation
,可以菊花链)并返回一些使用者的双倍值。我希望它只返回唯一的消费者,而我似乎找不到一种方法来使用Rails助手或正确的SQL来传递以获得我想要的。我觉得这里有一个简单的解决方案——这不是一个复杂的问题
我基本上想要Array#uniq
,但是对于ActiveRecord::Relation
。我尝试了一个select-DISTINCT语句
Consumer.joins(...).where(...).select('DISTINCT consumers.id')
它返回了正确的“university on consumers.id”属性,但它只返回了使用者id,因此当我最终加载关系时,使用者没有其他属性。
如果不选择“不同”:
my_consumer = Consumer.joins(...).where(...).first
my_consumer.status # => "active"
my_consumer = Consumer.joins(...).where(...).select('DISTINCT consumers.id').first
my_consumer.status # => ActiveModel::MissingAttributeError: missing attribute: status
使用select DISTINCT:
my_consumer = Consumer.joins(...).where(...).first
my_consumer.status # => "active"
my_consumer = Consumer.joins(...).where(...).select('DISTINCT consumers.id').first
my_consumer.status # => ActiveModel::MissingAttributeError: missing attribute: status
我不认为一个ActiveRecord::Relation
会比整个模型的加载量少,但我想select语句会这样。当我在select语句之后查询它所包含的类的关系时,它返回Consumer
,这似乎很奇怪
.select('DISTINCT consumers.*')