我的應用程式有一個 Group 物件,其中一個用戶有很多。導航欄顯示當前選擇了哪個組,各個頁面上顯示的物件都是以此為基礎的。我的許多模型都有“group_id”欄位,我希望這些欄位在保存時用當前選定組的 id 填充。
在我的應用程式控制器中,我有一個回傳 current_group 的 helper_method ,但是它不能也不應該從模型中訪問,這是我能想到的最干燥的方式。
#inhereted_model.rb
before_save :assign_group_reference
def assign_group_reference
self.group_id = current_group.id
end
有沒有一種我想念的有效和干燥的方法來做到這一點?
uj5u.com熱心網友回復:
你說的對; 任何控制器輔助方法都不能也不應該直接從模型方法訪問。
我認為標準的 DRY 方法是在 Controller 方法中設定模型的引數。例如,在控制器中執行以下操作:
# In a Controller
def my_helper(mymodel)
mymodel.group_id = current_group
# where current_group is your Controller helper method to obtain the group name.
end
def create # or update etc.
@mymodel = set_my_model # your arbitrary method to set a model
my_helper(@mymodel)
respond_to do |format|
if @mymodel.save
format.html { redirect_to @mymodel, notice: 'Success.' }
else
raise
end
end
end
如果需要,您可以結合使用or撰寫my_helper(在這種情況下不帶引數并設定實體變數@mymodel而不是區域變數),確保在設定模型后呼叫該方法,以避免在Controller中的許多方法中重復呼叫。before_actiononlyexcept@mymodelmy_helper
或者,如果您出于某種原因真的想在模型級別設定它,一個潛在的解決方法是使用 Ruby 執行緒變數,如下所示。
# In a controller
def create
model = set_my_model # Arbitrary routine to set a model
Thread.new{
Thread.current.thread_variable_set(:grp, current_group)
# where current_group is your Controller helper method to obtain the group name.
model.save!
# In the model, you define a before_save callback
# in which you write something like
# self.group_id = Thread.current.thread_variable_get(:grp)
}.join
end
但我認為這有點骯臟,原則上我會避免它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/408211.html
標籤:
上一篇:RailsZeitwerk蛇盒
