class Client < ActiveRecord::Base
has_many :hosts, :dependent => :destroy
end
class Host < ActiveRecord::Base
attr_accessible :client_id, :host, :is_embedded, :gmaps_key
belongs_to :client
end
正如您在上面的代码中所说,客户端可以拥有许多主机。我想弄清楚如何为主机设计我的控制器。最终目标是拥有多个“索引”页面,显示每个客户端的主机。我不需要一个页面来显示所有主机。你会怎么建议设置它?我应该做嵌套路由吗?
resources :clients do
resources :hosts
end
答案 0 :(得分:0)
使用一个简单的嵌套路线,就像你建议的路线一样,这样做是完美的。您需要修改HostsController
以仅加载指定客户端的主机:
# in app/controllers/hosts_controller.rb
def index
@hosts = Client.find(params[:client_id]).all
end
您可以通过http://example.com/clients/1/hosts访问该页面。很简单,没有?
答案 1 :(得分:0)
对我来说,最好的选择是嵌套路由 - 至少对于主机索引页面而言。如果您不想将整个主机资源嵌套在客户端下,那么您可以仅嵌套索引操作。例如:
resources :clients do
resources :hosts, :only => [:index]
end
resources :hosts, :except => [:index]
这意味着在您的HostsController中,client_id参数只会出现在索引操作中。所有其他操作只有主机的id参数。然后,您将使用以下URL查看客户端的所有主机:
http://localhost:3000/clients/10/hosts
您可以在单个主机上查看信息:
http://localhost:3000/hosts/291