如果我从 Rails 3 学到的一件事是,如果我在做某事时遇到困难,那我可能做错了。所以我正在寻求帮助。
我有一些模型在多对多关系中相关。
我能够毫无问题地在模型中创建关联。我的问题在于如何构建控制器来处理这些关系。如果您看不到我的目标,我会尝试举个例子。
例如...
class Account < ActiveRecord::Base
has_many :locations
end
class Contact < ActiveRecord::Base
has_many :locations
end
class Location < ActiveRecord::Base
has_and_belongs_to_many :accounts
has_and_belongs_to_many :contacts
end
假设我有上述模型。这将是我的资源...
resources :accounts do
resources :locations
end
resources :contacts do
resources :locations
end
resources :locations do
resources :accounts
resources :contacts
end
所以只是为了缩短一点,假设我想要一个帐户所有位置的列表。上述路线大概是 account/1/locations。因此将我降落在位置#index。
希望我在这一点上没有搞砸我的示例,但是构建此操作的最佳方法是什么,因为它确实有多个工作......至少是帐户、联系人和所有位置的位置。
所以我最终得到了这样的东西......
class LocationController < ApplicationController
def index
if params[:account_id]
@locations = Location.find_all_by_account_id(params[:account_id])
elsif params[:contact_id]
@locations = Location.find_all_by_contact_id(params[:account_id])
else
@locations = Location.all
end
respond_with @locations
end
end
更新#1:澄清一下,因为我得到了一些建议我改变我的模型关系的答案。我正在使用一个遗留系统,此时我无法更改关系。清理数据库和关系最终是我的目标,但现在我做不到。所以我需要找到一个适用于这种配置的解决方案。