I was writing an app that had a post model. The post model belongs to a “type.” In order to create my form for my post model, I needed to create a dynamic select field with my options coming from my type model.
Here’s how I did that.
First, in my controller, I got my types and put them in an instance variable to expose it to my view.
def new
@post = Post.new
@types = Type.all
end
Then, in my view, I had the form:
<%= form_with(model: @post, local: true) do |f| %>
<div class="form-group">
<%= f.label :title %><br/>
<%= f.text_field :title, class: "form-control" %>
</div>
<div class="form-group">
<%= f.select :type_id, @types.map { |t| [t.name, t.slug]}, {}, class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit class: "btn btn-primary" %>
</div>
<% end %>
Here, my form also includes a title. Also, I’m using Bootstrap for my form.
The important part – the part this post is focused on – is right here:
<%= f.select :type_id, @types.map { |t| [t.name, t.slug]}, {}, class: "form-control" %>
Here, we’re setting up a select tag and telling it to map to the :type_id param. Then we are passing an array of arrays that contain the name in the option as well as the value of the option.
This generates similar code to the following:
<option value="the-slug">the name </option>
And that’s how you can generate a dynamic select tag for your model-based form in Ruby on Rails.
For more Ruby on Rails and web development tips, make sure to follow me on Twitter.
Top comments (0)