简体   繁体   English

使用控制器的Rails 4关注DRY更新方法

[英]Rails 4 using controller concern to DRY update methods

I have a rails app where many of the models are editable using best_in_place, so I have a lot of controllers that look partially like this: 我有一个rails应用程序,其中许多模型可以使用best_in_place进行编辑,所以我有很多控制器看起来像这样:

before_action :find_objects, except: [:new, :create]

def update
  @object.update_attributes(object_params)
  respond_to do |format|
    format.json { respond_with_bip @object}
  end
end

private

def object_params
  params.require(:object).permit(:foo, :bar)
end

def find_objects
  @object = Object.find(params[:id])
end

How do I move this particular repeated piece into a controller concern, given that the object being updated is going to come in with a particular name in the params hash, and object_params and find_objects should call their proper versions based on the model name? 如果要更新的对象将在params散列中使用特定名称,并且object_params和find_objects应根据模型名称调用其正确的版本,如何将此特定重复的部分移动到控制器问题中? Is there some elegant meta-magic that'll sort this all out? 是否有一些优雅的元魔法可以解决这个问题?

I think this is a case where your code could be "too DRY". 我认为这是一个你的代码可能“太干”的情况。 You can certainly accomplish this using meta-magic, but it could make your code confusing in the long run. 你当然可以使用meta-magic来实现这一点,但是从长远来看它可能会使你的代码混乱。

If you want to do the meta-magic, one trick is to use params[:controller] to get the name of the model. 如果你想做元魔术,一个技巧是使用params[:controller]来获取模型的名称。 For example, if you have a PostsController , then: 例如,如果你有一个PostsController ,那么:

params[:controller] # => "posts"
params[:controller].classify # => "Post"

Taking this a step further, you could write a generic find_object like this: 更进一步,您可以编写一个通用的find_object如下所示:

def find_object
  model_class = params[:controller].classify.constantize
  model_instance = model_class.find(params[:id])
  instance_variable_set("@#{model_class.name.underscore}", model_instance)
end

But as I said at the beginning, I'm not sure I would recommend this amount of abstraction just for the sake of DRY-ing your controller code. 但正如我在开头所说的那样,我不确定为了干掉你的控制器代码我会推荐这么多的抽象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM