2

我在我的模型文件中创建了一个单表继承模型,并且在路由方面遇到了困难。当我在资源中使用 :as 时,它会重命名我的命名路径。

模型文件:

class Account < ActiveRecord::Base
    belongs_to :user
end
class AdvertiserAccount < Account
end
class PublisherAccount < Account
end

路由.rb

resources :advertiser_accounts, :as => "accounts" do
    resources :campaigns
end

我在路由中使用 :as,因为它是单表继承,我想传递 account_id 而不是advertisingr_account_id。我的链接是http://127.0.0.1:3000/advertiser_accounts/1/campaigns

/advertiser_accounts/:account_id/campaigns/:id(.:format)

但是,使用 :as 将我的命名路径从advertisingr_account_campaigns 重命名为account_campaigns。我的路线看起来像

account_campaigns GET /advertiser_accounts/:account_id/campaigns(.:format) campaigns#index

所以当我使用 form_for 创建一个新项目时,我会得到“未定义的方法 `advertiser_account_campaigns_path'”

编辑:当前被黑的解决方案

我正在使用的一种破解方法是复制路由文件中的代码。有人有建议吗?

resources :advertiser_accounts, :as => "accounts" do
    resources :campaigns
end
resources :advertiser_accounts do
    resources :campaigns
end
4

1 回答 1

0

如果您在设置中运行“rake routes”,您将看到:

   account_campaigns  GET        /advertiser_accounts/:account_id/campaigns(.:format)          campaigns#index
                      POST       /advertiser_accounts/:account_id/campaigns(.:format)          campaigns#create
 new_account_campaign GET        /advertiser_accounts/:account_id/campaigns/new(.:format)      campaigns#new
edit_account_campaign GET        /advertiser_accounts/:account_id/campaigns/:id/edit(.:format) campaigns#edit
     account_campaign GET        /advertiser_accounts/:account_id/campaigns/:id(.:format)      campaigns#show
                      PUT        /advertiser_accounts/:account_id/campaigns/:id(.:format)      campaigns#update
                      DELETE     /advertiser_accounts/:account_id/campaigns/:id(.:format)      campaigns#destroy
             accounts GET        /advertiser_accounts(.:format)                                advertiser_accounts#index
                      POST       /advertiser_accounts(.:format)                                advertiser_accounts#create
          new_account GET        /advertiser_accounts/new(.:format)                            advertiser_accounts#new
         edit_account GET        /advertiser_accounts/:id/edit(.:format)                       advertiser_accounts#edit
              account GET        /advertiser_accounts/:id(.:format)                            advertiser_accounts#show
                      PUT        /advertiser_accounts/:id(.:format)                            advertiser_accounts#update
                      DELETE     /advertiser_accounts/:id(.:format)                            advertiser_accounts#destroy

所以你应该在这个设置中使用“account_campaingns_path”,“:as”实际上改变了代码中的调用而不是url中的路径。如果你想改变路径,你应该使用":path =>" 而不是":as =>"。

Rails 路由指南还显示了一些带有“:as”和“:path”的示例以及生成的路径和帮助程序,您需要进行一些搜索,因为认为它们仅在解释其他情况的示例中使用。

编辑:重新阅读您的问题,我想您可能还想查看成员路由,我不确定这是否是您想要的意思,它是单一继承并且不想传递advertisingr_account 的':account_id'?

于 2012-04-01T07:23:24.323 回答