2

我有两个控制器,它们与我试图整合/“干燥”/重构/或其他任何东西基本相同。我搜索并找到了各种解决方案,但似乎无法实现其中任何一个。

需要合并的两个控制器的示例代码:

class ClientsController < ApplicationController
  before_filter :signed_in_user, only: [:show, :index, :edit, :update]

  def update
    @client = Client.find(params[:id])
    if @client.update_attributes(params[:client])
      flash[:success] = "Client updated"
      redirect_to @client
    else
      render 'edit'
    end
  end

end

~

class ItemCatsController < ApplicationController
  before_filter :signed_in_user, only: [:show, :index, :edit, :update]

  def update
    @item_cat = ItemCat.find(params[:id])
    if @item_cat.update_attributes(params[:item_cat])
      flash[:success] = "Item Category updated"
      redirect_to @item_cat
    else
      render 'edit'
    end
  end
end

我怀疑我需要做的是创建一个超级控制器,但我一直在寻找一种通用的方法来引用模型。任何帮助将不胜感激。

注意:我真的很想避免添加任何额外的宝石/插件来使其工作;我更喜欢“手动”/非魔法解决方案,以便我能理解到底发生了什么。

4

1 回答 1

2

如果您愿意使用 gem,请查看inherit_resources。除此之外,我建议保持原样。我不太可能通过尝试删除这一点样板来获得更好的代码。如果您看一下该 gem 的代码,您会发现其中涉及很多魔法——我怀疑一个家庭推出的解决方案会给您留下更多的代码行以及更复杂和更容易出错的代码,然后您现在拥有.

于 2013-06-10T20:07:17.147 回答