Note that there are some explanatory texts on larger screens.

plurals
  1. POHow should I structure controller actions that share templates?
    text
    copied!<p>Let's say I have a <code>User</code> model, and an <code>Invoice</code> model with a <code>belongs_to :user</code> association.</p> <p>Now I'm creating a <code>new</code> action for my <code>InvoicesController</code>, and the view that will be rendered. The view will have a select-element for selecting the user that this invoice will belong to.</p> <p>So I need to fetch those users somewhere; my instinct is to leave this kind of thing out of the view. I end up with this:</p> <pre><code>def new @users = User.all end </code></pre> <p>The form submit action is <code>create</code>. When the creation fails for some reason, I re-render the <code>new</code> action's view.</p> <pre><code>def create invoice = Invoice.new params[:invoice] if invoice.save flash[:notice] = 'Invoice created!' redirect_to :action =&gt; 'show', :id =&gt; invoice.id else @users = User.all render :action =&gt; 'new' end end </code></pre> <p>But as you can see, in order the re-render the <code>new</code> action, I have to fetch the users again.</p> <p>This is just an example, but consider that I have some forms with several select-elements filled from the database, or similar constructs. That turns into an awful lot of repetition.</p> <p>So how should I structure my controller in this situation?</p> <ul> <li>Should I simply use <code>User.all</code> from my view?</li> <li>Should I call <code>new</code> from within <code>create</code> to do the fetching for me?</li> <li>Or something else?</li> </ul>
 

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