1
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方式。

有没有更好的解决方案?

在此先感谢 最好的问候否认

4

2 回答 2

0

Rails 解决这个问题的方法是结合使用inherit_resources gem 和Responders继承资源的覆盖默认值部分中描述了您的用例。

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

于 2013-05-20T03:57:22.043 回答
0

我认为您正在寻找 before_filter。就像是:

before_filter :valid_user, only: [:index, :new, :show]

def valid_user
  redirect_to root_path if current_user.nil?
end
于 2013-05-20T04:18:24.717 回答