Ruby未定义方法(在模型中)

时间:2017-03-20 12:55:17

标签: ruby-on-rails ruby activerecord

我在尝试拨打我的" not_coworker_friend"时收到NoMethodError。或" coworker_friend"方法。我在Ruby MVC工作。这是我目前的代码,正如所写,它不会产生任何错误

class EmergencyTrip < ActiveRecord::Base

belongs_to :user

has_attached_file :receipt
validates_attachment_presence :receipt

validates_presence_of :trip_cost, :if => :not_coworker_friend
validates_presence_of  :phone_of_person, :if => :coworker_friend

def not_coworker_friend
  (self.ride_home_service == "co-worker/friend") ? false : true
end

def coworker_friend
  (self.ride_home_service == "co-worker/friend") ? true : false
end

end

我的目标是仅在&#34; not_coworker_friend&#34; == true。

第5行&amp; 6应该是:

...
has_attached_file :receipt, :if => :not_coworker_friend
validates_attachment_presence :receipt, :if => :not_coworker_friend
...

添加&#34;:if =&gt; not_coworker_friend&#34;对于那些行生成一个NoMethodError(未定义的方法`call&#39; for:not_coworker_friend:Symbol):,即使第8行和第8行没有抛出错误。 9.为什么这只会选择性地抛出错误?我怎么能纠正这个?

1 个答案:

答案 0 :(得分:2)

试试这个:

class EmergencyTrip < ActiveRecord::Base

    belongs_to :user

    has_attached_file :receipt, :if => Proc.new{|f| f.ride_home_service != "co-worker/friend"}
    validates_attachment_presence :receipt, :if => Proc.new{|f| f.ride_home_service != "co-worker/friend"}
end