0

I have a model called ToolFilter with a column of 'tool_type'. The string here refers to a class for a tool. I put a method in my application_controller called tools_list that gets the descendants of Tool.This works nicely in my frontend, but ToolFilter is complaining about the method tools_list.

class ToolFilter < ActiveRecord::Base
  validate :existence_of_tool
  def existence_of_tool
    unless tools_list.include? tool_type
      errors.add(:tool_type, "Invalid tool_type {{tool_type}}, use 'tools_list' to see a list of valid tool_object_types")
    end
  end

class ApplicationController < ActionController::Base
  helper_method :tools_list
  def tools_list
    Rails.application.eager_load!
    Tool.descendants
  end

It's a bit strange to tell a model about other classes in the file system, but I need to validate that it is one of these. Should I put tools_list is a module and include it in ToolFilter? Any suggestions?

TheJKFever
  • 685
  • 7
  • 25
  • I ended up creating a module for these methods to be used in the models instead of trying to call the ApplicationController (which just seems bad to do in a model). – TheJKFever Jul 17 '15 at 19:31

2 Answers2

1

Write this to include helper in your model

ApplicationController.helpers.tool_list

Though I will not recommend calling helper in model.

And checking tools with classes is damm bad idea.

Pardeep Dhingra
  • 3,916
  • 7
  • 30
  • 56
  • I agree it's definitely unconventional to check :tool_type against a class. But besides being unconventional, can you tell me why its a bad idea? I seem to have the proper validations and exceptions in place. Is it unreadable? – TheJKFever Jul 17 '15 at 19:30
0

I ended up creating a module called ToolExtention which has these helper methods in them. I then included this module in my controllers wherever it was needed and moved my logic from the views into the controller which I believe is better practice.

module ToolExtension
  def self.tools_list
    Rails.application.eager_load!
    Tool.descendants
  end
  ...

class ProjectsController < ApplicationController
  include ToolExtension
  ...
  ToolExtension.tools_list
TheJKFever
  • 685
  • 7
  • 25