user3868832
user3868832

Reputation: 620

why am i getting method undefined?

I am trying to call a method in a view from a model but I get this error

undefined method `titles_by_timing' for #<Class:0x0000010668db28>

I dont get why. I cant even call the method from the rails console.

[6] pry(main)> DeliveryCost.titles_by_timing
NoMethodError: undefined method `titles_by_timing' for #<Class:0x00000106f397b8>
from /Users/user/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.4/lib/active_record/dynamic_matchers.rb:22:in `method_missing'

Here is the model.

class DeliveryCost < ActiveRecord::Base

  before_destroy :survive_if_jobs

  has_many :job_delivery_costs
  has_many :jobs, through: :job_delivery_costs

  def titles_by_timing
    self.do stuff
  end

  private

  def survive_if_jobs
    jobs.empty?
  end

end

The view I am trying to call it from doesn't directly correspond to the model or controller, its called 'Job_delivery costs'.

- jdc_array = (@job.job_delivery_costs.any? ? [@job.job_delivery_costs,@job_delivery_cost].flatten : [@job_delivery_cost])
            - jdc_array.each do |jdc|
              = simple_form_for [:admin, @job, jdc] do |f|
                - if jdc.new_record?
                  %tr
                    %td
                      = f.input :delivery_cost_id, collection: DeliveryCost.order(:timing), :label_method => :timing, :value_method => :id, label: false
                    %td
                      = f.select :title, grouped_options_for_select(DeliveryCost.titles_by_timing)
                    %td
                      = f.input :cost_per_unit, label: false
                    %td
                      = f.input :hour_count, label: false
                    %td
                      = f.input :quantity, label: false
                    %td
                      = f.submit "Add", class: "btn btn-s btn-default" 

but that shouldn't matter should it? Its so frustrating.

Upvotes: 1

Views: 87

Answers (1)

Kirti Thorat
Kirti Thorat

Reputation: 53048

You have defined titles_by_timing as an instance method and are trying to use it as class method which is causing the error.

If you are planning to use it as a class method like DeliveryCost.titles_by_timing then you should be defining it as:

def self.titles_by_timing ## prefix with self
  self.do stuff
end

-OR-

If you wish to use titles_by_timing method as the way it is defined right now i.e., as an instance method then you should be calling the method on an instance of DeliveryCost

For example:

DeliveryCost.find(1).titles_by_timing

Upvotes: 6

Related Questions