2010-01-21 96 views
1

我有用於將當前的用戶到新創建的對象的簡單模塊:Ruby on Rails - 一個模型可以看到模塊,另一個模型不能?

module AttachUsers 

    def create_with_author(author, params) 
    created = new(params) 
    created.author = author 
    created.save 
    created 
    end 

    def create_with_author_and_editor(author, params) 
    created = new(params) 
    created.author = author 
    created.lasteditor = author 
    created.save 
    created 
    end 

end 

該模塊被直接lib目錄下保存爲attach_users.rb。

到目前爲止,我已經嘗試過使用這個模塊和兩個模型。它工作得很好,其中第一(評論)的模型,但是第二(頁)返回錯誤信息

undefined method `create_with_author_and_editor' 

我已在在我的每個型號的頂部如下:

extend AttachUsers 

@comment = @post.comments.create_with_author(current_user, params[:comment]) 

並在頁面控制器是這樣的::

在評論控制器這樣使用它

任何人都可以看到爲什麼它可能無法正常工作?這是我第一次嘗試使用模塊,很抱歉,如果它是顯而易見的。

任何意見讚賞。

感謝

+0

哪裏模塊保存? – Matchu 2010-01-21 23:05:35

+0

直接在lib目錄下 – Dan 2010-01-21 23:11:19

回答

2

嘗試使用include AttachUsers代替extend AttachUsers

此外,這不是我會這樣做的方式。使用關聯擴展可能會更好。

module CreateWithAuthorAndEditor 
    def create_with_author(author, params) 
    create(params.merge({ :author => author }) 
    end 
end 

class Post< ActiveRecord::Base 
    has_many :comments :extend => CreateWithAuthorAndEditor 
end 

然後,您可以撥打:

post.comments.create_with_author(current_user, params[:comment]) 
+0

謝謝。我以前沒有聽說過這些。我會檢查出來的! – Dan 2010-01-21 23:17:13

+0

我不確定,很難說出你的代碼在評論中做了什麼。 – jonnii 2010-01-21 23:20:01

+0

@Dan,僅供參考,'extend'將方法有效地添加爲類方法,'include'將方法添加爲實例方法。所以如果你想'Page.create_with_author_and_editor'你想使用'extend'。 – 2010-01-22 23:00:13

相關問題