Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I pass parameters to nested resources for single table inheritance in Ruby on Rails?
    text
    copied!<p>I am having some difficulties passing in parameters to my controller. I created an Single table inheritance model in my model file.</p> <pre><code>class Account &lt; ActiveRecord::Base belongs_to :user end class AdvertiserAccount &lt; Account end class PublisherAccount &lt; Account end </code></pre> <p>I setted up my routes table with nested resources</p> <pre><code>resources :advertiser_accounts do resources :campaigns end </code></pre> <p>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 <a href="http://127.0.0.1:3000/advertiser_accounts/1/campaigns" rel="nofollow">http://127.0.0.1:3000/advertiser_accounts/1/campaigns</a> Since my resource for the url is advertiser_accounts and not accounts, I am not able to get the parameter :account_id. </p> <pre><code>class CampaignsController &lt; ApplicationController def index @account = current_user.accounts.find_by_id(params[:account_id]) end end </code></pre> <p>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.</p> <p><strong>Edit Possible solution:</strong> 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. </p> <p>routes.rb</p> <pre><code>resources :advertiser_accounts, :type =&gt; "AdvertiserAccounts" do resources :campaigns end </code></pre> <p>campaigns_controller.rb</p> <pre><code>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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload