LoginSignup
0
0

More than 1 year has passed since last update.

【コピペ】Railsで選択肢を追加していく方法

Last updated at Posted at 2021-09-10

Ruby on Railsで選択肢を追加していく方法

実装後参考サイト https://vlogmatome.herokuapp.com/posts/new

目次

1.コントローラーを準備する

2.モデル・データベース周り

3.viewのコード

4.ルートをかく

実装

1.コントローラーを準備する

まずはコントローラーを準備します。
今回はブランドを投稿していくWebサイトを作成します。
ブランドの選択肢を投稿ごとに追加していきます。

ブランドの投稿はpostsコントローラー。選択肢の追加はbrandsコントローラーで行っていくこととします。
それでは早速コードを書いてみましょう。

posts_controller.rb
class PostsController < ApplicationController
  def index
    @posts = Post.all
    @brands = Brand.all
    @brand = Brand.where(brand:"")
  end

  def new
    @post = Post.new
    @brand = Brand.new
  end

  def create
    post = Post.new(post_params)

    if post.save
      redirect_to :action => "index"
    else
      redirect_to :action => "new"
    end
  end

  private
  def post_params
    params.require(:post).permit(:brand, :brand_id)
  end
end
brands_controller.rb
class BrandsController < ApplicationController
  def index
    @brands = Brand.all
  end

  def create
    brand = Brand.new(brand_params)
    if brand.save
        redirect_to action: "index"
    else
        redirect_to action: "new"
    end
  end

  private
  def brand_params
    params.require(:brand).permit(:brand, :brand)
  end
end

2.モデル・データベース周り

まずはpostsテーブルにinteger型でbrandというカラムとbrand_idというカラムを作成します。
次にbrandsテーブルにstring型でbrandをいうカラムを作成してください。
準備ができてらそれぞれのモデルに以下のコードを書いてみましょう。
モデルの関連づけを行います。

posr.rb
class Post < ApplicationRecord
    belongs_to :brand
end
brand.rb
class Brand < ApplicationRecord
    has_many :posts
end

3.viewのコード

続いてはveiwページです。

posts/index.html.erb
<div class="posts-container">
  <% @posts.each do |t| %>
    <br>
    <% t.brand %>
  <% end %>

  <h2>Brand別一覧</h2>  
      <% @size = @brands.length - 1 %>
      <% for b in 0..@size do %>
        <%= @brands[b].brand %>

        <% @brands[b].posts.compact.each do |t| %>
         <% t.brand %>
        <% end %>
      <% end %>
</div>
posts/new.html.erb
<%= form_for @brand do |brand| %>
    <div class="field">
      <%= brand.label :brand %>
      <%= brand.text_field :brand, :size => 10 %>
    </div>
    <%= brand.submit "追加する" %>
<% end %>

<%= form_for @post do |f| %>

    <div class="field">
      <%= f.label :brand %>
      <%= f.collection_select(:brand_id, Brand.all, :id, :brand) %>
    </div>

    <%= f.submit "投稿する" %>
<% end %>

4.ルートをかく

最後にルートを書いていきます。

routes.rb
Rails.application.routes.draw do
  resources :posts
  resources :brands
end

以上です!

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0