如何在Rails中创建自己的方法,如model.association.build



我想知道是否有一些标准的方法可以创建方法,比如在has_many关联上生成的build方法。为了便于说明,假设以下设置

class Post < ActiveRecord::Base
 has_many :comments
end
class Comment < ActiveRecord::Base
 belongs_to :post
end

Rails自动生成post.comments.build方法。有没有一种标准的方法或Rails方法来创建我自己的方法?我通过在comments对象的singleton类上定义方法进行了尝试,如下所示:

class Post < ActiveRecord::Base
 after_initialize do
  class << comments
   def go
    #do something where I can access the the 'owning' post object
   end
  end
 end
end

但在ActiveRecord更新后,这段代码似乎中断了。所以,我想知道是否有更好的方法。

您可以通过将块传递给has_many方法调用并定义方法来将方法添加到关联中。以the docs:为例

has_many :employees do
  def find_or_create_by_name(name)
    first_name, last_name = name.split(" ", 2)
    find_or_create_by(first_name: first_name, last_name: last_name)
  end
end

最新更新