ruby-on-railsaxlsx

Is it possible to apply filters on a model inside a view in Ruby on Rails?


Is it possible to apply filters on a model inside a view's code:

I use axlsx to generate Excel and I tried something like this inside my myview.xlsx.axlsx file:

fs = MyModel.where(:Column1 => v1, :Column2 => v2)
puts fs[0].Column1

I got an error

undefined method Column1 for nil:NilClass

I am pretty sure there's nothing wrong with my filter so I wonder is it legal to have such a filter inside a view (and if such filters should only be placed inside a controller instead)?


Solution

  • It's legal, yet not advisable to use queries in the view. It's better to move them to a controller and even better to wrap them in a method inside the model.

    In your case it looks that the query returns an empty collection, and that's why fs[0] is nil and you cannot call a method on it.