当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - Use default values in method from association or XYZ

问题描述:

In my code, Author has_many Books, so I could do something like:

@author.books

If the author has no books, when @author.books is called, I'd like a default book object with that author's info already filled out (i.e. author_id), something like:

class Author < ActiveRecord::Base

has_many :books

def books

the_books || default_book

end

end

That's obviously not real code, but it demonstrates what I'm trying to do.

网友答案:

How about:

class Author < ActiveRecord::Base
  has_many :books
  alias :__books__ :books

  def books
    result = __books__
    result.empty? ? default_books : result
  end

  private
  def default_books
    # ...
  end
end
分享给朋友:
您可能感兴趣的文章:
随机阅读: