ruby-on-rails – Ruby(Rails)将属性委派给另一个模型的方法?
-编辑-
从第一个答案中阅读了Delegate方法后,我的问题是,是否可以将两种不同的方法委托给另一种方法. IE:我目前有:@ photo.attachment.file.url和@ photo.attachment.height和@ photo.attachment.width 我想要通过@ photo.file.url,@ photo.file.height,@ photo.file.width访问所有这些. 语法的原因是Attachment是一种使用Paperclip管理文件的模型,Paperclip正在生成.file方法(该模型称为Attachment,该模型使用Paperclip的has_attached_file:文件). – 原始问题 – 我想知道Ruby中的别名方法和属性(我认为这是一个普遍的ruby问题,尽管我的应用程序在Rails 3中): 我有两个型号:照片has_one附件. 附件具有“height”和“width”属性和“file”方法(来自Paperclip). 因此,默认情况下,我可以访问附件模型的位,如下所示: photo.attachment.width # returns width in px photo.attachment.height # returns height in px photo.attachment.file # returns file path photo.attachment.file.url #returns url for the default style variant of the image photo.attachment.file.url(:style) #returns the url for a given style variant of the image 现在,在我的照片课上,我创建了这个方法: def file(*args) attachment.file(*args) end 所以,现在我可以简单地使用: photo.file # returns file path photo.file.url # returns file url (or variant url if you pass a style symbol) 我的问题是,我能够将photo.attachment.file直接引导到photo.file,但是我也可以将height和width映射到photo.file,以便为了一致性,我可以访问height和width属性通过photo.file.height和photo.file.width? 这是可能的事情,如果是这样的话呢? 解决方法
所以你问的是那个
photo.file --> photo.attachment.file photo.file.url --> photo.attachment.file.url photo.file.width --> photo.attachment.width 你不能用代理人来解决这个问题,因为你希望这个文件是根据下面的内容来表示不同的东西.要实现这一点,您将需要重新打开纸张,我不会推荐(因为我相信api是好的方式). 我可以想到的唯一办法就是解决这个问题,就是添加消除文件级别.像这样: photo.width --> photo.attachment.width photo.file --> photo.attachment.file photo.url --> photo.attachment.file.url 然后,您可以通过为每个想要的方法使用代理来解决. 所以你写 class Photo delegate :width,:height,:file,:to => :attachment delegate :url,:to => :'attachment.file' end 希望这可以帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |