如果未设置关联,则创建模型方法

时间:2016-01-05 02:33:30

标签: ruby-on-rails associations

我有一个Post模型belongs_to :author。如果在创建期间将作者设置在帖子上,post.author将返回作者。但是,如果作者没有设置在帖子上,我希望在调用post.author时仍然返回默认作者。我有以下内容:

class Post
  belongs_to :author

  def author
    begin
      Author.find(read_attribute("author_id"))
    rescue
      Author.default_author
    end
  end
end

我的问题是是否可以覆盖关联方法author。这是否会导致关联等内部处理被绕过?有一个更好的方法吗?例如,我应该使用类似method_missing的内容吗?

3 个答案:

答案 0 :(得分:1)

我将before_validation设置为空白

class Post < ActiveRecord::Base
  belongs_to :author

  before_validation :set_author
  validates :author, :presence => true

  def set_author
    self.author = Author.default if author.blank?
  end

end

答案 1 :(得分:1)

#app/models/post.rb
class Post < ActiveRecord::Base
   before_create :set_author, unless: Proc.new {|post| post.author.present? }

   private

   def set_author
      self.author_id = "2"
   end
end

答案 2 :(得分:0)

在您的特定情况下,我不会推荐

  

覆盖关联方法作者

与数据库中的列具有相同的名称,因为如果您认为另一位开发人员落后于您,那么在post上调用author属性并不仅仅返回author列的数据就不明显了,但实际上它会返回默认作者,如果它不存在。

因此,我会说你需要创建一个名为author_or_default_author之类的新方法,因此希望该方法返回的内容很明显

此外,当您只是尝试创建作者记录时,覆盖模型中的列名实际上将运行该代码。无论这是否可取,对于另一位开发者来说,这绝对不是显而易见的

你可能会考虑做这样的事情

class Post
  belongs_to :author

  def author_or_default_author
    Author.where(id: author_id).present? || Author.default_author
  end
end

并用

调用它
post.author_or_default_author

在上面的示例中使用.where的一个好处是,如果在1234无效时尝试了Author.find(1234),则不必处理activerecord not found类型的错误。作者身份。所以你可以摆脱你正在使用的begin and rescue

相关问题