Ruby on rails 通过方法链接将方法合并到一个散列
我有一个类正在为数据库生成查询: 它们应该连接在一起,所以我不会重复查询代码(DRY) 我想我可以这样做: 红宝石 结果应该是一个散列:Ruby on rails 通过方法链接将方法合并到一个散列,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个类正在为数据库生成查询: 它们应该连接在一起,所以我不会重复查询代码(DRY) 我想我可以这样做: 红宝石 结果应该是一个散列: {user_id: 1, scope: false} 您只需要创建作用域 class Blah < ActiveRecord::Base scope :no_scope, -> {all} scope :for_user, -> (user_id) {where(user_id: user_id)} end Blah
{user_id: 1, scope: false}
您只需要创建作用域
class Blah < ActiveRecord::Base
scope :no_scope, -> {all}
scope :for_user, -> (user_id) {where(user_id: user_id)}
end
Blah.no_scope.for_user(1) # where(user_id: 1)
class Blah{all}
作用域:for_user,->(user_id){where(user_id:user_id)}
结束
Blah.无范围。用于用户(1)#其中(用户id:1)
另请参见您是否试图实现此目标
class Blah < ActiveRecord::Base
scope :no_scope, -> { where(scope: false) }
scope :for_user, -> (id) { where(user_id: id) }
end
Blah.no_scope.for_user(1) # where(scope: false, user_id: 1)
class Blah{where(作用域:false)}
作用域:for_user,->(id){where(user_id:id)}
结束
Blah.no_scope.for_user(1)#where(scope:false,user_id:1)
要将结果作为实际哈希而不是Activerecord关系给出,可以这样做
class Blah < ActiveRecord::Base
scope :no_scope, ->{where(scope: false)}
scope :for_user, ->(id){where(user_id: id)} # no space in ->(id)
end
# give results as an array of hashes
Blah.no_scope.for_user(1).map { |e| {scope: e.scope, user_id: e.user_id} }
class Blah < ActiveRecord::Base
scope :no_scope, -> { where(scope: false) }
scope :for_user, -> (id) { where(user_id: id) }
end
Blah.no_scope.for_user(1) # where(scope: false, user_id: 1)
class Blah < ActiveRecord::Base
scope :no_scope, ->{where(scope: false)}
scope :for_user, ->(id){where(user_id: id)} # no space in ->(id)
end
# give results as an array of hashes
Blah.no_scope.for_user(1).map { |e| {scope: e.scope, user_id: e.user_id} }
[{"scope"=>false, "user_id"=>1}]