我有一个模型团队和部门描述为一个部门应该有很多团队:
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}
来获取团队分工的名称,以包含在字符串中,但它根本不起作用。
给出错误:
NoMethodError (undefined method `division' for #<Class:0x007f80179b68f8>):
即使我使用#{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和paperclip以及这个解决方案似乎仍然在表单上抛出关于gsub的错误。我找到了另一个线程Dynamic use of :default_url in Paperclip来解决我的问题。 shioyama的解决方案在没有rails_admin的情况下工作正常。
答案 0 :(得分: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。