close
close

Building Nested Shapes in Rails with Stimulus

Building Nested Shapes in Rails with Stimulus

This article was originally published on the Rails Designer Blog. Rails Designer is the first professionally designed UI component library for Rails.


In a previous article I wrote about nested forms with Turbo and no other dependencies. This is a great solution that works remarkably well, but I want to explore another option using Stimulus.

Why explore another option? While the Turbo solution works great, there may be cases where the round trip to the server is too much for simple, static HTML. After all, no additional data from the server is needed to render the nested fields.

Let’s build the same function, but now with Stimulus instead of Turbo.

Image description

For the purposes of this article, I’m going to assume you have a modern Rails app and the following basics in place:

  • Questionnaire; rails generate model Survey name
  • Ask; rails generate model Question survey:belongs_to content:text

To update the survey model:

class Survey  ApplicationRecord
  has_many :questions
  accepts_nested_attributes_for :questions
end
Go to full screen mode

Exit full screen

Add a simple controller to it. rails generate controller Surveys show new. Then update it as follows:

class SurveysController  ApplicationController
  def show
    @survey = Survey.find(params(:id))
  end

  def new
    @survey = Survey.new
  end

  def create
    @survey = Survey.new(survey_params)

    if @survey.save
      redirect_to @survey
    else
      render :new
    end
  end

  private

  def survey_params
    params.require(:survey).permit(:name, questions_attributes: (:content))
  end
end
Go to full screen mode

Exit full screen

As mentioned in the previous article, make sure that the survey_params are as set above.

Now update the two views:

h1>New Survey/h1>


  
div> div>/div>

div> div> %= form.submit %>

Enter fullscreen mode Exit fullscreen mode

And the show action (just so there's something to see after create):

h1>%= @survey.name %>


  

question.content %>

% end %>
Go to full screen mode

Exit full screen


🧑‍🎨✨ Want to improve the UI of your Rails app? Rails Designer can help. Explore all the options today. ✌️


And as a final step you add resources :surveys, only: %w(show new create) Unpleasant configuration/routes.rb (and delete the generated routes).

Now that all the basic functions are present, it is exactly the same as before with the article, only with the Turbo version.

Nested forms using stimulus

The approach will be to _questions_fields partly in a