user1157352
user1157352

Reputation: 149

How can I pass parameters to nested resources for single table inheritance in Ruby on Rails?

I am having some difficulties passing in parameters to my controller. I created an Single table inheritance model in my model file.

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

I setted up my routes table with nested resources

resources :advertiser_accounts do
    resources :campaigns
end

I want to be able to pass the current account_id (an account_id from one of my two subclasses of account) to my campaign controller file. A URL that I would use is http://127.0.0.1:3000/advertiser_accounts/1/campaigns Since my resource for the url is advertiser_accounts and not accounts, I am not able to get the parameter :account_id.

class CampaignsController < ApplicationController
def index
    @account = current_user.accounts.find_by_id(params[:account_id])
end
end

is there a shortcut to get the current resource or the id? Am I passing in parameters correctly? It seems confusing to call many find_by_id in the controller. Any help is appreciated.

Edit Possible solution: One of the solutions that I was thinking was setting a type in my routes and then in my controller I would use case statement then get params[:advertiser_account_id] but that seems very tedious and messy. Especially if I will need to copy and paste a list of case statements in each action.

routes.rb

resources :advertiser_accounts, :type => "AdvertiserAccounts" do
    resources :campaigns
end

campaigns_controller.rb

def index
    case params[:type]
     when "AdvertiserAccounts"
            @account = current_user.accounts.find_by_id(params[:advertiser_account_id])
     when "PublisherAccounts"
            @account = current_user.accounts.find_by_id(params[:publisher_account_id])
    end
end

Upvotes: 1

Views: 1475

Answers (2)

Bogdan Popa
Bogdan Popa

Reputation: 1099

You can try with "becomes" method in your controller. In your private method where you're looking for the account_id you would have:

@account = Account.find(params[:account_id]).becomes Account

Upvotes: 0

Alex Marchant
Alex Marchant

Reputation: 2510

Try this out:

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

that should give you

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

Upvotes: 1

Related Questions