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.

Version

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 ...

thread.rb


class Thread < ApplicationRecord
	belongs_to :category
end

category.rb


class Category < ApplicationRecord
	has_many :threads
end

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

--Routing

routes.rb


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

--Controller

ruby:categories.controller.rb


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

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

	def index
		@categories = Category.all
	end

	private
	def category_params
		params.require(:category).permit(:name)
	end
end

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

ruby:new.html.erb


<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>
		<div class="form_action row">
			<%= f.submit "sign up", class: "btn col-sm-12 submit_btn" %>
		</div>
	<% end %>
</div>

--List page

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

I wish I could display this for the time being

index.rb


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

Create a thread submission form

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

--Controller

threads_controller.rb


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

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

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

  private
  def board_params
    params.require(:thread).permit(:title,:body)
  end
end

--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.

ruby:threads/new.index.erb


<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>
		<div class="form_input">
			<%= f.label :body %>
			<%= f.text_area :body, class: "form-control" %>
		</div>
		<div class="form_input">
			<%= f.label :category_id %>
			<%= f.collection_select :category_id, Category.all, :id, :name,
															:include_blank => "Please select a category" %>
		</div>
		<div class="form_action row">
			<%= f.submit "Post", class: "btn col-sm-12 submit_btn" %>
		</div>
	<% end %>
</div>

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
How to create a form to select a date from the calendar
I want to give a class name to the select attribute
[Rails] I want to send data of different models in a form
I want to use a little icon in Rails
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
Preparing to create a Rails application
[Rails] [bootstrap] I want to change the font size responsively
[Rails] I tried to create a mini app with FullCalendar
I want to call a method and count the number
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
[Rails 6.0, Docker] I tried to summarize the Docker environment construction and commands necessary to create a portfolio
I want to add a browsing function with ruby on rails
[Rails 6] How to create a dynamic form input screen using cocoon
(Ruby on Rails6) Create a function to edit the posted content
I want to develop a web application!
I want to write a nice build.gradle
I want to write a unit test!
[rails] How to create a partial template
[Rails] I learned about migration files! (Adding a column to the table)
I want to select multiple items with a custom layout in Dialog
I want to create a dark web SNS with Jakarta EE 8 with Java 11
I thought about the best way to create a ValueObject in Ruby
[Rails] How to create a table, add a column, and change the column type
I want to introduce the committee with Rails without getting too dirty
I want to output the day of the week
[For beginners] I want to automatically enter pre-registered data in the input form with a selection command.
[Rails] How to create a graph using lazy_high_charts
[Rails] I tried to raise the Rails version from 5.0 to 5.2
I want to simply write a repeating string
I tried to create a LINE clone app
The code I used to connect Rails 3 to PostgreSQL 10
I want to design a structured exception handling
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 import the pull-down menu items when submitting a form in Rails into CSV and display them from the DB data.
[Android] I want to create a ViewPager that can be used for tutorials
[Rails / JavaScript / Ajax] I tried to create a like function in two ways.
[Rails / ActiveRecord] I want to validate the value before the type is converted (_before_type_cast)
I want to be able to read a file using refile with administrate [rails6]
I want to play a GIF image on the Andorid app (Java, Kotlin)
A memo to simply create a form using only HTML and CSS in Rails 6
I want to create the strongest local development environment using VSCode Remote Containers
Rails6 I want to make an array of values with a check box
I want to recursively get the superclass and interface of a certain class
[Introduction] Try to create a Ruby on Rails application
3. Create a database to access from the web module
I want to call a method of another class
[Rails] How to create a signed URL for CloudFront
[Java] I want to calculate the difference from the date
I want to embed any TraceId in the log
I tried to decorate the simple calendar a little
Reasons to include ActiveModel :: Model to create a Form object
I want to judge the range using the monthly degree