2016-01-05 62 views
1

我有一個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的東西嗎?

回答

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 
+0

這對我最適合......謝謝。 – Anand

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 
+0

感謝擺脫begin and rescue的,我措辭問題的方式,你是對的。但是,在我的實際情況中,default_author是帖子本身的功能。所以,有些時候,我在創建帖子之前無法獲取default_author。 – Anand

+0

您可以根據帖子的參數創建或找到默認作者嗎?或者你需要它在數據庫出於某種原因? – Swards

0

你的具體情況,我不會推薦

重寫關聯方法作者

與與數據庫中的列名稱相同,因爲如果您想到另一位開發者落後對於他們來說,在post上調用author屬性並不僅僅是返回author列的數據並不明顯,但如果它不存在,它實際上會返回默認作者。

因此,對於這個原因,我會說你需要創建一個名爲像author_or_default_author所以很希望很明顯那是什麼方法將返回

此外,覆蓋在你的模型,列名會實際上運行該代碼時,一種新的方法你只是試圖創建一個作者記錄。這是否將是可取與否也絕對不會是公然明顯另一開發商

您可以考慮

post.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 

,把它在我上面的示例中使用.where的地方是,如果您在1234不是有效作者ID時嘗試使用Author.find(1234),則不必處理activerecord not found類型的錯誤。所以,你可以在你使用

相關問題