Rails 3 - 创建自己的模型并与他人合作
我有两个表用于检查视图(页面的访问) - 画廊和摄影师(PhotographerView)中图片(PhotoView)的视图。 因为这两个模型(和表)是相同的,所以我想为它们创建一个模型 - 类似于:
class Func < ActiveRecord::Base
def self.check_views(model_view, data)
last_view = model_viewView.where('ip_address = ? AND request_url = ?', request.remote_ip, request.url).order('created_at DESC').first
unless last_view
model_view+View.new(...).save
model_view.increment_counter(:views, data.id)
else
if (DateTime.now - last_view.created_at.to_datetime) > 1.day
model_view+View.new(...).save
model_view.increment_counter(:views, data.id)
end
end #comparing dates
end
end
并调用此方法,如下所示:
@photo = Photo.find(params[:id])
Func.check_views('Photo', @photo)
当我尝试按照上面的方式使用它时,我会收到错误未定义Func(Table 不存在):Class 的方法 `check_views'
你能给我一个帮助吗,如何让它工作? 谢谢
I have two tables for checking views (visits of the page) - views of pic (PhotoView) in gallery and photographers(PhotographerView).
Because these two models (and tables) are the same, I want to create a model for them - something like:
class Func < ActiveRecord::Base
def self.check_views(model_view, data)
last_view = model_viewView.where('ip_address = ? AND request_url = ?', request.remote_ip, request.url).order('created_at DESC').first
unless last_view
model_view+View.new(...).save
model_view.increment_counter(:views, data.id)
else
if (DateTime.now - last_view.created_at.to_datetime) > 1.day
model_view+View.new(...).save
model_view.increment_counter(:views, data.id)
end
end #comparing dates
end
end
and call this method like:
@photo = Photo.find(params[:id])
Func.check_views('Photo', @photo)
When I try use it with the way above, I'll get the error undefined method `check_views' for Func(Table doesn't exist):Class
Could you give me a help, how to make it work?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
ActiveRecord::Concern
和模块将常用功能移至一处,如下所示:您现在可以执行以下操作:
You can use
ActiveRecord::Concern
and modules to move the common functionality into one place as follows:you can now do the following:
我很想将其作为扩展需要视图功能的类的模块来执行此操作。像下面这样的东西应该可以工作;但它完全未经测试,并且完全不同于我以前做过的任何事情,因此它可能完全有问题。公平警告。
(
extend
将目标Module
的所有实例方法添加为调用类的类方法;因此Photo
获得Photo.check_views( data)
,该函数中的self
是Photo
类。)I'd be very tempted to do this as a module extending the classes which want the Views functionality. Something like the following ought to work; but it's entirely untested and entirely unlike anything I've ever done before so it may be completely buggy. Fair warning.
(
extend
adds all the instance methods of the targetModule
as class methods of the calling class; soPhoto
gainsPhoto.check_views(data)
, andself
in that function is the classPhoto
.)