为什么我的方法未定义?

时间:2014-07-24 19:58:51

标签: ruby-on-rails ruby forms rails-activerecord

我正在尝试从模型中调用视图中的方法,但是我收到此错误

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

我不明白为什么。我甚至无法从rails控制台调用该方法。

[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'

这是模型。

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

我试图将其称为“不”直接对应于模型或控制器的视图,其名称为“Job_delivery”&#39;

- 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" 

但这应该不重要吗?它太令人沮丧了。

1 个答案:

答案 0 :(得分:6)

您已将titles_by_timing定义为实例方法,并尝试将其用作导致错误的类方法

如果您计划将其用作类方法,例如DeliveryCost.titles_by_timing,那么您应该将其定义为:

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

-OR-

如果您希望使用titles_by_timing方法作为现在定义的方式,即作为实例方法,那么您应该在{{1}的实例上调用该方法}

例如:

DeliveryCost