Biju
Biju

Reputation: 1008

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)?

Upvotes: 0

Views: 87

Answers (2)

You can have such code in views, although you should try to avoid having logic in the view and move it to the controller or a helper. The problem here is that the active record relation is empty:

fs = MyModel.where(:Column1 => v1, :Column2 => v2) #=> #<ActiveRecord::Relation []>
fs[0] #=> nil

You can use try to avoid that an exception is raised if the relation is empty and return nil instead:

fs[0].try(:Column1) #=> nil

Upvotes: 3

mrzasa
mrzasa

Reputation: 23327

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.

Upvotes: 0

Related Questions