[英]Rails 3.2: How do I access the current model instance inside of a helper module?
在我的rails模型Post.rb
我設置了以下方法:
def category_names(seperator = ", ")
categories.map(&:name).flatten.join(seperator).titleize
end
def publish_date
read_attribute(:publish_date).strftime('%A, %b %d')
end
我想將它們移到PostsHelper
下的PostsHelper
模塊中。 但是,這樣做時會出現無方法錯誤,因為我猜對self
的引用丟失了。
那么我該如何解決呢? 輔助模塊是否適合這些方法?
如果我沒有記錯的話,輔助方法主要設計用於視圖中。
我確定的是,您的輔助方法不在模型的范圍內,這意味着您需要向其傳遞要使用的屬性。 例:
def category_names(categories, seperator = ", ")
categories.map(&:name).flatten.join(seperator).titleize
end
並在您的視圖中調用:
category_names @post.categories
如果您發現自己的視圖中未專門使用自寫的“幫助程序”方法,則可以創建服務對象並將其包含在模型中。
編輯:服務對象
您可以在“ app”目錄下創建“ services”目錄,並在此處創建類。
讓我給你舉個例子。 我有一個User模型類,並且想將所有與密碼相關的方法歸類到UserPassword服務對象中。
用戶類別:
class User < ActiveRecord::Base
include ::UserPassword
...
end
UserPassword服務對象:
require 'bcrypt'
module UserPassword
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
module ClassMethods
def authenticate(email, password)
user = find_by_email email
if user and user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
end
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
因此,我的User 實例對象 (即u = User.first
)可以調用u.encrypt_password
,而我的User 類可以調用User.authenticate
。
也許還有其他方法,但是我發現它很靈活,易於編寫和維護:)
助手總是旨在幫助視圖,但是,如果您希望模型干凈並且將無關的方法分開保存,請嘗試在Rails 3中使用關注點。默認情況下,關注目錄會出現在Rails 4中。
DHH有一篇不錯的博客文章。
http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.