Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.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 将参数化视图与Hanami存储库一起使用_Ruby_Postgresql_Sql Parametrized Query_Hanami - Fatal编程技术网

Ruby 将参数化视图与Hanami存储库一起使用

Ruby 将参数化视图与Hanami存储库一起使用,ruby,postgresql,sql-parametrized-query,hanami,Ruby,Postgresql,Sql Parametrized Query,Hanami,我在我的PostgresDB中准备了名为user\u details的视图。我创建了UserDetail实体和UserDetailRepository。在这里,您缩短了我的视图的版本,以可视化我的问题: CREATE VIEW user_details AS SELECT id, user_name FROM users WHERE user_name like '$1#%' 我的问题是如何使用Hanami存储库注入参数 我可以在这里描述的repos中使用原始sql,但我更喜欢使用迁移在pos

我在我的PostgresDB中准备了名为
user\u details
的视图。我创建了
UserDetail
实体和
UserDetailRepository
。在这里,您缩短了我的视图的版本,以可视化我的问题:

CREATE VIEW user_details AS
SELECT id, user_name FROM users WHERE user_name like '$1#%'
我的问题是如何使用Hanami存储库注入参数


我可以在这里描述的repos中使用原始sql,但我更喜欢使用迁移在postgres中创建视图。我不想改进查询,但想知道是否可以使用Hanami实现用户参数化查询。感谢您的所有回答

PostgreSQL不支持您描述的参数化视图。它可以具有调用函数的视图,该函数可以访问当前会话状态,并且您可以在从视图中选择数据之前设置该状态。但是,我建议您使用参数来定义方法

class UserRepo
  def user_details(prefix)
    root.project { [id, user_name] }.where { user_name.ilike("#{ prefix }%") }.to_a
  end
end
你得到的基本上是一样的。如果您想使用
user\u details
作为基本关系,您可以在回购协议上定义一个私有方法,并从其他公共方法调用它

class UserRepo
  def user_details_filtered(user_name, min_user_id = 0)
    user_details(prefix).where { id > min_user_id }.to_a
  end

  def user_details_created_after(user_name, after)
    user_details(prefix).where { created_at > after }.to_a
  end

  private 

  # Don't call this method from the app code, this way
  # you don't leak SQL-specific code into your domain
  def user_details(prefix)
    root.project { [id, user_name] }.where { user_name.ilike("#{ prefix }%") }
  end
end