HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Initialise simple_form object inline

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simple_forminlineinitialiseobject

Problem

Using Rails 4 and a simple form, I'm rendering a couple of forms outside of their native controllers. Rather than scattering initialisers through my controllers, I wondered if it is cleaner to do the following:

Solution

I do stuff like that myself sometimes, but I'm not proud of it.

Strictly speaking it is the controller's responsibility to set up the new record. The controller should be be the sole source of whatever (primary) data the view needs. Instantiating a new record is business logic, not presentation logic.

In a similar vein, if we consider a simple blogging app, it'd be fine for the view to access secondary data, like:



But I think you'd agree that it absolutely shouldn't be doing something like:

 


Your code basically the same as the latter of those two examples. Although it seems less extreme, in both cases the view is doing the job of the controller.

Also: Assuming a typical Rails setup, your form is in its own partial, and you include it in both the edit and new views when rendering. Now, when editing, the @event_submission variable absolutely should exist - it should be set by the controller. It makes no sense for the form to create it. And when one "invocation" of the form requires it, it makes no sense for the other invocation to make it optional. So basically, the form requires an @event_submission variable - doesn't matter if it's new or not.

Letting for form instantiate the record also opens the door for hidden bugs and unintended behavior. If you navigate to /event_submissions/123/edit (or whatever the path is), but the controller somehow doesn't set the @event_submission to be edited, the form will just create its own. This means that:

  • You won't get an error (though you should!) because the form absorbed it. Your tests may even pass.



  • The form will be blank, which it shouldn't be when editing.



  • And since it's inferred that a form for a new record should point to the create action, if you submit the form, you're creating a new record when all you wanted was to edit one.



Everything works, there are no errors, but it's not at all doing what it's supposed to. Have fun debugging :)

Besides, your code works for HTML via ERB. But if you want a different format, or use a different templating language, you may not get away with it anymore. Since you'll then have to do the initialization in the controller anyway, you might as always do that.

Code Snippets

<% @post.comments.each do |comment| %>
<% Post.find(params[:id]).comments.each do |comment %> <!-- please don't do this -->

Context

StackExchange Code Review Q#65082, answer score: 2

Revisions (0)

No revisions yet.