简体   繁体   中英

Ransack Search Date as a String

I am using ransack gem for search mechanism in my app. The problem im facing is that in my model i have accidently created the "date" column as string field due to which Date search isn't working and im not able to do the comparison on the basis of date. Since the data type of column is string so ransack do not bring appropriate results.

@q = MyModel.order(id: :desc).ransack(params[:q])
@records = @q.result(distinct: true)

I have tons of live data in that Table and i don't want to risk it by writing a migration. Any help will be appreciated

There is a simple hack you can use it and convert the string into data at the database level. Your model you need to add below method.

ransacker :name_of_your_column_to_d do
    Arel.sql("cda")
end

Then in your controller do the below changes.

# You can use DESC id if you want to change order. 
@q = YourModel.ransack({s: "id DESC"}.merge(params[:q] || {}))

@q.result(distinct: true).select("*, to_date(\"your_model_table_name\".\"your_date_column_name\", 'MM/DD/YYYY') as cda, your_model_table_name.id")

Let me know if you need further assistance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM