Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 基于单个列强制关系的唯一性_Ruby On Rails_Ruby On Rails 3_Activerecord - Fatal编程技术网

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.*')