I want to create a form to select the [Rails] category

Hello. I'm currently building a bulletin board in Rails.

I wanted to classify the threads on the bulletin board by category and display them, so I implemented it with the intention of selecting the category when creating threads.

I've started to touch Rails recently, so if you are familiar with it, please ask Masakari.


Ruby 2.5 Rails 5.1

DB / preparation

Designed with many threads tied to a category スクリーンショット 2020-07-09 12.08.06.png

Don't forget to set between models ...


class Thread < ApplicationRecord
	belongs_to :category


class Category < ApplicationRecord
	has_many :threads

First, register the category

It won't start without a category, so let's register. You can use it from the console, but I think I'll add more categories in the future, so I'll create a registration form. After registering, you will be taken to the list page.

First, write routes and controller



Rails.application.routes.draw do
  root 'thread#index'
  resources :thread #I also write thread routing
  resources :categories



class CategoriesController < ApplicationController
	def new
		@category = Category.new

	def create
		@category = Category.new(category_params)
		if @category.save
			redirect_to categories_path, notice: "Has registered"
			render :new

	def index
		@categories = Category.all

	def category_params

スクリーンショット 2020-07-09 12.26.28.png


<div class="col-sm-12">
	<h2 class="text-center">Add category</h2>
	<%= form_with model: @category, local: true do |f| %>
		<div class="form_input">
			<%= f.label :name %>
			<%= f.text_field :name, class:"form-control" %>
		<div class="form_action row">
			<%= f.submit "sign up", class: "btn col-sm-12 submit_btn" %>
	<% end %>

--List page

スクリーンショット 2020-07-09 12.28.24.png

I wish I could display this for the time being


	<% @categories.each do |category| %>
		<%= category.name %>
	<% end %>

Create a thread submission form

Now that you've registered, you'll be able to select a category on the thread's post form.



class ThreadsController < ApplicationController
  def new
    @thread = Thread.new

  def create
    @Thread = Thread.new(board_params)
    if @thread.save
      redirect_to thread_path(@thread), notice: "Post has been completed"
      render :new

  def show
    @thread = Thread.find(params[:id])

  def board_params

--Posting page

スクリーンショット 2020-07-09 12.36.23.png

You can create a selection form with collection_select.

As for how to use it, I use it like this ... collection_select (object name, method name, array of elements, value attribute item, text item [, option or HTML attribute or event attribute])

In this example, Category.all corresponds to the" array of elements "part. Perhaps, rather than writing Category.all, put it in a variable on the controller and use it in view. It may be better to have a shape like that.

It would be helpful if someone could point out here.


<div class="col-sm-12">
	<h2 class="text-center">Make a thread</h2>
	<%= form_with model: @thread, local: true do |f| %>
		<div class="form_input">
			<%= f.label :title %>
			<%= f.text_field :title, class: "form-control" %>
		<div class="form_input">
			<%= f.label :body %>
			<%= f.text_area :body, class: "form-control" %>
		<div class="form_input">
			<%= f.label :category_id %>
			<%= f.collection_select :category_id, Category.all, :id, :name,
															:include_blank => "Please select a category" %>
		<div class="form_action row">
			<%= f.submit "Post", class: "btn col-sm-12 submit_btn" %>
	<% end %>

You will be able to select as follows.

スクリーンショット 2020-07-09 12.37.45.png

in conclusion

Thank you for watching until the end. I will write a lot of articles from now on, and I will output more and more.

Recommended Posts

I want to create a form to select the [Rails] category
I want to give a class name to the select attribute
I want to define a function in Rails Console
I want to create a generic annotation for a type
I want to add a delete function to the comment function
I want to create a Parquet file even in Ruby
[Rails] I want to display the link destination of link_to in a separate tab
(Ruby on Rails6) Create a function to edit the posted content
[rails] How to create a partial template
I want to introduce the committee with Rails without getting too dirty
How to easily create a pull-down in Rails
I want to play with Firestore from Rails
[Rails] How to create a Twitter share button
I want to truncate after the decimal point
[Rails] I want to load CSS with webpacker
I want to get the value in Ruby
I want to create the strongest local development environment using VSCode Remote Containers
I want to recursively get the superclass and interface of a certain class
I want to call the main method using reflection
I want to click a GoogleMap pin in RSpec
[Rough commentary] I want to marry the pluck method
I want to return the scroll position of UITableView!
I want to simplify the log output on Android
I want to hit the API with Rails on multiple docker-composes set up locally
Create a method to return the tax rate in Java
I want to use the sanitize method other than View.
A series of steps to create portfolio deliverables with Rails
I want to get a list of the contents of a zip file and its uncompressed size
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I want to put the JDK on my Mac PC
[Rails] How to display the list of posts by category
Implemented a strong API for "I want to display ~~ on the screen" with simple CQRS
I want to recursively search the class list under the package
Tutorial to create a blog with Rails for beginners Part 2
I want to return a type different from the input element with Java8 StreamAPI reduce ()
Click the [rails] button to create a random alphanumeric password and enter it in the password field
I want to transition to the same screen in the saved state
I want to use FireBase to display a timeline like Twitter
I tried to create a padrino development environment with Docker
I want to return multiple return values for the input argument
[Ruby] I want to reverse the order of the hash table
How to create a method
Tutorial to create a blog with Rails for beginners Part 0
I want to pass the startup command to postgres with docker-compose.
I want to simplify the conditional if-else statement in Java
[Enum_help] Use enum_help to create a select box displayed in Japanese!
[Eclipse] I want to open the same file twice [Split editor]
Easy way to create a mapping class when using the API
I tried to build a simple application using Dockder + Rails Scaffold
I want to limit the input by narrowing the range of numbers
I made a reply function for the Rails Tutorial extension (Part 5):
I want to add the disabled option to f.radio_button depending on the condition
I tried to understand how the rails method "link_to" is defined
I want to add devise in Rails, but I can't bundle install
[Rails] Don't use the select method just to narrow down the columns!
I want to remove the top margin in Grouped UITableView (swift)
[Java] I tried to make a maze by the digging method ♪
I tried to move the Java compatible FaaS form "Fn Project"
I want to control the default error message of Spring Boot
I made a tool to output the difference of CSV file
[Rails] I want to add data to Params when transitioning with link_to