模型中未定义的方法

时间:2014-05-10 20:25:09

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我尝试更改回形针文件夹的路径:

     has_attached_file :image,
:path => ":rails_root/public/system/#{self.patient}/:style/:filename",
    :styles => {.....

但不知怎的,我得到了这个错误:

NoMethodError (undefined method `patient' for #<Class:0x692c328>):
app/models/photo.rb:4:in `<class:Photo>'
app/models/photo.rb:1:in `<top (required)>'
app/controllers/patients_controller.rb:24:in `show'

我不明白为什么,我的完整型号代码:

class Photo < ActiveRecord::Base
    belongs_to :patient
    has_attached_file :image,
    :path => ":rails_root/public/system/#{self.patient}/:style/:filename",
:styles => {
  :thumb    => ['100x100>',  :jpg, :quality => 70],
  :preview  => ['480x480>',  :jpg, :quality => 70],
},
:convert_options => {
  :thumb    => '-set colorspace sRGB -strip',
  :preview  => '-set colorspace sRGB -strip',
}
   validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]

   def patient
     self.patient.id
   end

end

1 个答案:

答案 0 :(得分:1)

你的问题在这里:

:path => ":rails_root/public/system/#{self.patient}/:style/:filename"

代码在声明时间推断#{self.patient},而不是在运行时。由于在声明时,self属于类Class,因此会出现未定义的方法错误。

我不确定它会起作用,但你可以试试:

:path => ":rails_root/public/system/:patient/:style/:filename"

无论如何,你可以查看这个问题:Rails 3, Paperclip - Custom Interpolations