基于自我连接的Ruby on Rails路由

3

我在正在开发的应用中使用了自连接和交集表,如下所示:

class User < ActiveRecord::Base
  has_many :clients, :through => :client_relationships, :conditions => "approved='1'", :source=>:user
end

我的意思是说,我可以使用@current_user.clients命令获取所有客户端的信息。但是,我想设置一个URL /clients,以便列出当前用户的所有客户端。有人知道我该如何做吗?

我已经尝试在我的路由中设置:clients资源和客户端控制器,但是由于没有客户端模型,它会报错。

1个回答

0

不应该有任何错误。

# routes.rb
map.resources :clients

# clients_controller.rb
class ClientsController < ApplicationController
  def index
    @clients = @current_user.clients
  end

  # other actions...
end  

# clients index.html.erb
<% @clients.each do |c| %>
  <p><%= c.name %></p>
<% end %>

好的,我已经成功让它工作了。我正在使用CanCan进行基于角色的授权,并在控制器顶部使用load_and_authorize_resource方法,该方法必须假定每个控制器都有一个模型。但是我遇到了一种奇怪的行为,就是在索引操作中,我可以访问current_user,但无法访问@current_user,尽管在我所有其他的控制器中我都使用@current_user。你知道这可能是为什么吗? - John
没事了,我想我已经弄明白了。其他控制器有一个before_filter设置了@current_user变量。 - John

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接