【问题标题】:How to short the Controller actions in Rails如何缩短 Rails 中的控制器操作
【发布时间】:2013-05-20 02:04:44
【问题描述】:
def index
    @customers = current_user.customers
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @customers }
    end
  end

  def show
    @customer = current_user.customers.find(params[:id])
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @customer }
    end
  end

  def new
    @customer = current_user.customers.new
  end

这是我的 CustomerController 的一小部分。来源@customers@customers = customers 等等。

我只想为 current_user 索引/显示/新建。这是有效的,但我必须手动更改所有控制器操作。 而且我所有的自动化规范文件都只是测试@customer = customers

这似乎不是手动更改所有这些的 Rails 方式。

有没有更好的解决方案?

提前致谢 最好的祝福 否认

【问题讨论】:

  • 你能澄清你到底在问什么吗?

标签: ruby-on-rails-3 controller ruby-on-rails-3.2


【解决方案1】:

Rails 解决此问题的方法是将inherited_resources gem 与Responders 结合使用。 Overwriting Defaults section of inherited_resources 中描述了您的用例。

José Valims 的书 Crafting Rails Applications: Expert Practices for Everyday Rails Development 中的“使用响应程序和生成器编写 DRY 控制器”一章也讨论了这种方法。

【讨论】:

    【解决方案2】:

    我认为您正在寻找 before_filter。比如:

    before_filter :valid_user, only: [:index, :new, :show]
    
    def valid_user
      redirect_to root_path if current_user.nil?
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多