2013-12-10 86 views
0

此问题是由于前一个(Return url from paperclip to json)的后果而产生的。我正在总结,以便更容易遵循,也因为这只是上述提到的一部分。我有一个使用回形针进行多图像上传的CMS系统。我的代码是来自关联模型的呼叫实例方法

asset.rb

attr_accessible :asset_content_type, :asset_file_name, :asset_file_size, :asset_updated_at, :place_id, :asset 
    belongs_to :place 
    has_attached_file :asset 

    validates_attachment :asset, :presence => true, 
    :content_type => { :content_type => ['image/jpeg', 'image/png'] }, 
    :size => { :in => 0..1.megabytes } 

def asset_url 
asset.url(:original) 
end 

place.rb

has_many :assets 
    accepts_nested_attributes_for :assets, :allow_destroy => true 

def avatar_url 
asset_url 
end 

places_controller

def overall_photos 
    @places = Place.all 
    render :json => @places.to_json(:methods => [:avatar_url]) 
    end 

错误我获取当我尝试访问...地方/ overall_photos.json是{“状态”:“500”,“错误”:“未定义的局部变量或方法`asset_url'为#\ u003CPlace:0x007f163b67d8a8 \ u003E”}所以它似乎我无法通过关联模型place.rb访问asset.rb的实例方法。任何人都可以指向正确的方向吗?我甚至试图让asset_url成为一个类方法,但仍然没有运气。

+0

鉴于一个地方has_many资产,你对什么'asset_url'应该返回给定的地方的意图是什么? –

+0

要为特定类(例如资产)调用实例方法,您需要该类的一个实例。 – Slicedpan

+0

最好我想所有的asset_urls返回。 – user3077352

回答

0
def avatar_url 
    assets.map(&:asset_url) 
end 

这应该给你,你根据你的评论

+0

非常感谢您的支持。有效。 – user3077352

+0

不要忘记标记为已回答然后 – Slicedpan

+0

由于我以前没有做过,我该怎么做? – user3077352

0

如果您希望所有资产的URL想要的东西:

def asset_urls 
    self.assets.map {|a| a.asset_url } 
end 

但你可能只需要一个作为头像,所以我使用

def avatar_url 
    self.assets.first.asset_url if self.assets.first #to avoid calling asset_url on Nil 
end