Note that there are some explanatory texts on larger screens.

plurals
  1. PODRYing up routes and javascript responses
    primarykey
    data
    text
    <p>I'm not sure if I'm missing a known design pattern, but I keep coming up against the following problem with RESTful routes Rails.</p> <p>In my example, I have a users controller that can respond in javascript (:js) format. The default response populates a page element with a list of the paginated users:</p> <pre><code># /app/controllers/users_controller.rb class UsersController &lt; ActionController def index @users = User.paginate(:all, :page =&gt; params[:page], :conditions =&gt; ['name ILIKE ?', params[:name]) respond_to do |format| format.html format.js end end end </code></pre> <p>The corresponding RJS template would look like:</p> <pre><code># /app/views/users/index.js.rjs page.replace_html :users, :partial =&gt; 'users' </code></pre> <p>This works fine, allowing me to perform AJAX lookups on users. However, in another part of my site (say the user editing form) I would like to perform an AJAX lookup of users, but update a set of ''select'' options or perform an inline autocomplete, rather than update the #users page element, e.g.</p> <pre><code># /app/views/users/edit.html.erb &lt;%= f.text_field :name %&gt; $('#user_name').autocomplete({url: '/users', data: 'name=value', ...}) </code></pre> <p>My question is what would be the best DRY way to achieve this? I don't think I should need to create a new controller action to correspond to the different view, as this would involve repeating the finder code. The only solution I've come across so far is to build some javascript conditions into my RJS helper:</p> <pre><code># /app/views/users/index.js.rjs page &lt;&lt; "if($('#users').length &gt; 0)" page.replace_html :users, :partial =&gt; 'users' page &lt;&lt; "else" page.replace_html :user_options, :partial =&gt; 'user_options_for_select' </code></pre> <p>This feels very brittle, and unclean for Rails. Am I missing something in how I can respond with different views depending on the calling controller?</p> <p>Appreciate any help! Chris</p>
    singulars
    1. This table or related slice is empty.
    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.
    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