Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In Rails routing, a 'resource' refers to the standard 7 routes that are created for RESTful resources: <code>index</code>, <code>show</code>, <code>new</code>, <code>create</code>, <code>edit</code>, <code>update</code> and <code>destroy</code>. Normally that is enough, but sometimes you might want to create another action.</p> <p>In the model, you want to create a <code>scope</code> that only returns special users:</p> <pre><code>class User &lt; ActiveRecord::Base scope :special, where(:special =&gt; true) end </code></pre> <p>On the controller side, there are two ways to go about this. What you are suggesting is the creation of an additional action:</p> <pre><code>match "/users/special" =&gt; "users#special" resource :users </code></pre> <p>In the controller, your special action would return the scope you just created:</p> <pre><code>class UsersController &lt; ApplicationController def special @users = User.special end end </code></pre> <p>That will do what you ask, but I would suggest NOT doing it this way. What if you add other flags later that you want to search by? What if you want to search by multiple flags? This solution isn't flexible enough for that. Instead, keep the routes the way they are:</p> <pre><code>resource :users </code></pre> <p>and just add an additional line to your controller:</p> <pre><code>class UsersController &lt; ApplicationController def index @users = User.all @users = @users.special if params[:special] end end </code></pre> <p>and now, when you want to display special users, simply direct the user to <code>/users?special=true</code></p> <p>This approach is much more future-proof, IMO.</p> <p>(This answer is assuming Rails-3. If you're still using 2.3 let me know)</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.
 

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