Note that there are some explanatory texts on larger screens.

plurals
  1. PORails Controller action: Customize key in params hash
    primarykey
    data
    text
    <p>I'm working on a Rails 3.1.x app and I have the following set of models:</p> <pre><code>class Widget include Mongoid::Document field :name embeds_many :comments end class ShinyWidget &lt; Widget; end class DullWidget &lt; Widget; end class Comment include Mongoid::Document field :message embedded_in :widget end </code></pre> <p>So basically I need to allow comments to be associated with different types of widgets. Using the standard resources in my routes such as:</p> <pre><code>resources: widgets do resources :comments end </code></pre> <p>That exposes urls such as <code>GET /widgets</code>, <code>GET /widgets/:widget_id/comments</code>, etc. However, I'd like to expose an API for adding comments to different types of widgets. I'd like those API URL's to look something like:</p> <pre><code>GET /shinywidgets/:widget_id/comments POST /shinywidgets/:widget_id/comments </code></pre> <p>However, I'm ok with having a ShinyWidgetsController and a DullWidgetsController, but I'd like to only create a single CommentsController. Since I haven't thought of a nice way of having a single CommentsController to handle comments for different types of widgets, I tried this:</p> <pre><code>resources :widgets do get 'comments', to: 'widgets#comments_index' post 'comments', to: 'widgets#comments_create' end </code></pre> <p>When doing a POST to /widgets/:widget_id/comments the <code>params</code> hash stores the comment data that's being posted in a key named <code>widget</code> instead of what I was hoping for <code>comment</code>.</p> <p>I know if used <code>resources :comments</code> Rails would change that key in the <code>params</code> hash to be <code>comment</code>, but can I tell Rails what to name that key given my current setup?</p> <p>Currently I have to create a comment doing something like this:</p> <pre><code>def comments_create widget = Widget.find(params.delete :widget_id) comment = widget.comments.create(params[:widget]) end </code></pre> <p>I'd really like to have:</p> <pre><code>comment = widget.comments.create(params[:comment]) </code></pre> <p>Any thoughts?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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