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

时间:2015-02-25 08:53:32

标签: ruby-on-rails

我想知道是否有一些标准的方法可以创建像has_many关联生成的构建方法之类的方法。为了说明,假设以下设置

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更新后,这段代码似乎破了。所以,我想知道是否有更好的方法。

1 个答案:

答案 0 :(得分:0)

您可以通过将块传递给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