简体   繁体   English

访问Rails类/模型方法

[英]Accessing Rails Class/Model Methods

I am new to rails and am figuring out the best ways to write certain methods. 我是Rails的新手,正在寻找编写某些方法的最佳方法。

I am trying to write a method that belongs to a certain model and can be accessed without initiating an instance. 我正在尝试编写一种属于某个模型的方法,并且可以在不启动实例的情况下对其进行访问。 So far I have this under my class PaymentNotification < ActiveRecord::Base 到目前为止,我在我的类PaymentNotification <ActiveRecord :: Base下

def url
   url_for(:controller => 'payment_notifications', :only_path => false)
end

The problem here is that I need to do this to access the url 这里的问题是我需要执行此操作才能访问网址

n = PaymentNotification.new
n.url

In my code, I want to be able to write PaymentNotification.url to access the method relevant to that model. 在我的代码中,我希望能够编写PaymentNotification.url来访问与该模型相关的方法。

Maybe I am thinking about this the wrong way and someone can guide me. 也许我在想这是错误的方法,有人可以指导我。 Basically, what I am trying to achieve is that each model can have its set of methods and attributes so that they all are organized and I know from the code which file each method is declared in, instead of just calling a 基本上,我想要实现的是每个模型都可以具有其方法和属性集,以便它们都可以被组织起来,而且我从代码中知道每个方法都声明在哪个文件中,而不仅仅是调用

payment_notification_url

which may be located in any of the irrelevant initialization files. 它可以位于任何不相关的初始化文件中。 I saw helper methods but it seems like i still won't be able to use a dot syntax and will have to write something like "payment_notification_url" to access my url 我看到了辅助方法,但似乎我仍然无法使用点语法,并且必须编写类似“ payment_notification_url”的内容来访问我的网址

Any ideas on the best way to go about doing this? 关于最佳方法的任何想法吗?

You need to define a class method via the self keyword. 您需要通过self关键字定义一个类方法。

def self.url
   url_for(:controller => 'payment_notifications', :only_path => false)
end

Then you can use PaymentNotification.url 然后,您可以使用PaymentNotification.url

class A
  def self.a
    p "Class method"
  end

  def b
    p "Instance Method"
  end
end

A.a   #Class method
#A.b #NoMethodError

a = A.new
a.b #Instance Method
#a.a    #NoMethodError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM