ActiveRecord user-supplied column name

后端 未结 1 1492
梦毁少年i
梦毁少年i 2021-01-14 11:26

I am trying to allow the end-user of a rails app to limit results based on the value of an arbitrary column. At its simplest, I want to do something roughly equivalent to:

1条回答
  •  心在旅途
    2021-01-14 11:59

    To prevent sql injection, you should validate the column is a valid one

    valid_cols = ["c1", "c2"]
    valid_cols.include?(column) or raise "Bad query"
    

    Then you can just use the query interface as before

    Model.where("#{column} >= ?", min)
    

    0 讨论(0)
提交回复
热议问题