2012-08-27 60 views
0

沮喪我有一個模特隊和司描述爲一個部門應該有很多球隊:Rails的:是與NoMethodError(未定義的方法...)錯誤

class Team < ActiveRecord::Base 
    belongs_to :division 

    has_attached_file :logo, :styles => { :large => "120x180>", :thumb => "100x100>", :tiny => "25x25>" }, 
     :url => "/assets/images/:style/teams/#{self.division.name}/:basename.:extension", 
     :path => ":rails_root/public/assets/images/teams/#{self.division.name}/:basename.:extension" 
end 


class Division < ActiveRecord::Base 
    has_many :teams 
end 

我想要得到的區劃名稱團隊使用:#{self.division.name}包括在字符串中,但它根本不起作用。鑑於

錯誤:

​​

即使我使用#{self.name}得到了球隊的名字,但它僅返回類名稱:"Team"。在控制檯中,我打電話給他們就好了:

1.9.3p194 :009 > team = Team.find(4) 
    Team Load (0.3ms) SELECT `teams`.* FROM `teams` WHERE `teams`.`id` = 4 LIMIT 1 
=> #<Team id: 4, name: "Arsenal F.C.", league_id: nil, division_id: 1, stadium_id: 2, history: "This is Arsenal F.C. history file", wins: 1, losses: 1, win_percentage: 1.0, created_at: "2012-08-25 09:25:22", updated_at: "2012-08-27 01:54:08", logo_file_size: 29303, logo_updated_at: "2012-08-27 01:54:08", logo_content_type: "image/png", logo_file_name: "arsenal.png"> 
1.9.3p194 :010 > team.name 
=> "Arsenal F.C." 
1.9.3p194 :011 > team.division.name 
    Division Load (0.3ms) SELECT `divisions`.* FROM `divisions` WHERE `divisions`.`id` = 1 LIMIT 1 
=> "English Premier Division" 
1.9.3p194 :012 > 

我想在team.rb調用self.name(球隊名稱)或self.division.name(團隊分工的名稱),而不是一個控制器。

任何想法爲什麼?由於自己還沒有加載?如何解決這個問題?

更新:我真的很喜歡shioyama的解決方案,因爲我們可以將Proc傳遞給回形針。然而,我的rails_admin和回形針和這個解決方案似乎仍然在表單上拋出關於gsub的錯誤。我發現另一個線程Dynamic use of :default_url in Paperclip,將涵蓋我的問題。 shioyama的解決方案工作正常,沒有rails_admin。

回答

2

當您在類定義中使用self時,它引用類本身,而不是該類的實例。要獲取實例,則必須使用lambda

has_attached_file :logo, 
    :styles => { :large => "120x180>", :thumb => "100x100>", :tiny => "25x25>" }, 
    :url => lamda { |attachment| 
    team = attachment.instance 
    "/assets/images/:style/teams/#{team.division.name}/:basename.:extension" 
    }, 
    :path => lambda { |attachment| 
    team = attachment.instance 
    ":rails_root/public/assets/images/teams/#{team.division.name}/:basename.:extension" 
    } 

attachment.instance獲取附件被附加到實例(在這種情況下Team類的實例)。請參閱paperclip documentation

請看這個回答:can you pass self to lambda in rails?

相關問題