[英]Rails 4 Controller Concern initializer
I would like to add a status concern to various controllers since all of these controllers share the same status functionality. 我想对各种控制器添加状态关注,因为所有这些控制器共享相同的状态功能。
A status can be "active", "inactive" or "archived". 状态可以是“活动”,“非活动”或“已存档”。 If added to a specific controller ex. 如果添加到特定控制器,例如。 bars_controller these methods would look like this: bars_controller这些方法看起来像这样:
def activate
@bar.activate!
redirect_to(:back)
end
def deactivate
@bar.deactivate!
redirect_to(:back)
end
def archive
@bar.archive!
redirect_to(:back)
end
I have moved the above to my concern called Foo and I've included Foo in my controller like this: 我已经将以上内容移到我关注的Foo上,并将Foo包含在控制器中,如下所示:
include Foo
The issue I have when moving these methods to a concern, is that the Model instance is not defined. 将这些方法转移到关注点时,我遇到的问题是未定义Model实例。
How do I generalize the "@bar" section of the code in my concern? 我如何在我所关心的地方泛化代码的“ @bar”部分? This will enable me to use the concern for multiple Model instances including Baz. 这将使我能够将关注点用于包括Baz在内的多个Model实例。 I tried using "self" but that references the Controller instance and not the Model instance. 我尝试使用“ self”,但它引用了Controller实例而不是Model实例。
Your concern could look like this: 您的担忧可能是这样的:
module Foo
extend ActiveSupport::Concern
def activate
render text: bar.to_json
end
def deactivate
render text: bar.to_json
end
def archive
render text: bar.to_json
end
private
def bar
# 'demodulize' isn't necessary if you're working outside of namespaces
params[:controller].classify.demodulize.constantize.find(params[:id])
end
end
And your routes would benefit from using a concern as well: 您的路线也会因为使用关注而受益:
concern :statusable do
member do
get :activate
get :deactivate
get :archive
end
end
resources :alphas, :bravos, :charlies, concerns: :statusable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.