Fakhir Shad Fakhir Shad - 1 year ago 115
Ruby Question

Ransack Search Date as a String

I am using ransack gem for search mechanism in my app. The problem i m 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 i m 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

Answer Source

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download