TheJKFever
TheJKFever

Reputation: 705

Rails Model needs to validate includes? class_name

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?

Upvotes: 0

Views: 87

Answers (2)

TheJKFever
TheJKFever

Reputation: 705

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

Upvotes: 0

Pardeep Dhingra
Pardeep Dhingra

Reputation: 3946

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.

Upvotes: 1

Related Questions