我有一个部分需要运行一些控制器逻辑才能正常渲染。是否有某种方法可以将部分与渲染时运行的某些控制器逻辑相关联?
例如,这就是我当前的代码:
我的数据控制器:
class MyDataController < ApplicationController
def view
@obj = MyData.find(params[:id])
run_logic_for_partial
end
def some_method_i_dont_know_about
@obj = MyData.find(params[:id])
# Doesn't call run_logic_for_partial
end
def run_logic_for_partial
@important_hash = {}
for item in @obj.internal_array
@important_hash[item] = "Important value"
end
end
end
view.html.erb:
Name: <%= @obj.name %>
Date: <%= @obj.date %>
<%= render :partial => "my_partial" %>
some_method_i_dont_know_about.html.erb:
Name: <%= @obj.name %>
User: <%= @obj.user %>
<%# This will fail because @important_hash isn't initialized %>
<%= render :partial => "my_partial" %>
_my_partial.html.erb:
<% for item in @obj.internal_array %>
<%= item.to_s %>: <%= @important_hash[item] %>
<% end %>
即使没有从控制器显式调用该方法,如何确保在渲染run_logic_for_partial
时调用它?_my_partial.html.erb
如果我不能,Rails 中是否有任何常见的模式来处理这些情况?