0

我有一个模型团队和部门描述为一个部门应该有很多团队:

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

知道为什么吗?因为self还没有加载?如何解决这个问题?

更新:我真的很喜欢 shioyama 的解决方案,因为我们可以将 Proc 传递给回形针。但是,我的 rails_admin 和回形针和这个解决方案似乎仍然在表单上抛出关于 gsub 的错误。我在 Paperclip中找到了另一个线程Dynamic use of :default_url可以解决我的问题。shioyama 的解决方案在没有 rails_admin 的情况下也能正常工作。

4

1 回答 1

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类的实例)。请参阅回形针文档

另请参阅此答案:您可以将 self 传递给 rails 中的 lambda 吗?

于 2012-08-27T02:46:47.910 回答