【Rails】카테고리 기능

소개



레시피 게시 사이트를 만들고 레시피에 연결하는 카테고리 기능을 구현합니다.
gem의 ancestry는 사용하지 않습니다.
Recipe 모델과 User 모델이 연결되어 있어, 1 유저가 복수 투고할 수 있는 사양입니다. 그 주변은 할애하겠습니다.
투고(Recipe)와 카테고리(Category)의 모델, 콘트롤러는 실장 완료로 진행시키고 받고, 이번은 투고와 카테고리의 연결에 대한 내용에 중점을 두어 Qiita 투고하겠습니다.

완성 이미지



입력 양식

레시피 목록


중간 테이블 만들기



recipe_category_relations 테이블을 중간 테이블로 가정합니다.
$ rails g model Recipe_category_relation recipe_id:integer category_id:integer

db/schema.rb
 create_table "categories", force: :cascade do |t|
    t.string "category_name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "recipe_category_relations", force: :cascade do |t|
    t.integer "recipe_id"
    t.integer "category_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "recipes", force: :cascade do |t|
    t.string "recipe_title"
    t.text "recipe_body"
    t.string "image_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "recipe_food"
  end


게시물 모델, 중간 테이블, 카테고리 테이블 연결



app/models/recipe.rb
class Recipe < ApplicationRecord
  has_many :recipe_category_relations
  has_many :categories, through: :recipe_category_relations
end

app/models/recipe_category_relation.rb
class Recipe_category_relation < ApplicationRecord
  belongs_to :recipe
  belongs_to :category
end

app/models/category.rb
class Category < ApplicationRecord
  has_many :recipe_category_relations
  has_many :recipes, through: :recipe_category_relations
end

through: :recipe_category_relations 의 기술로, 중간 테이블 recipe_category_relation 를 경유해 recipe 와 category 를 관련지을 수가 있습니다.

보기에 표시



app/views/recipes/new.html.erb
<h1>レシピ投稿</h1><br>
 <%= form_with model:@recipe, url: recipes_path , local:true do |f| %>
   <%= f.attachment_field :image %>
   <%= f.label :title, '料理名'%>
   <%= f.text_field :recipe_title, class:"form-control", placeholder:"料理名" %>
   <%= f.label :category, 'カテゴリ' %>
   <%= f.collection_check_boxes(:category_ids, Category.all, :id, :category_name) do |category| %>
     <%= category.label do %>
       <%= category.check_box %>
       <%= category.text %>
     <% end %>
   <% end %>
   <%= f.label :body, '材料'%>
   <%= f.text_area :recipe_food, class:"form-control", placeholder:"材料をここに" %>
   <%= f.label :body, '作業工程'%>
   <%= f.text_area :recipe_body, class:"form-control", placeholder:"作業工程をここに" %><br>
   <%= f.submit "レシピ投稿", class: "btn btn-warning" %>
 <% end %>

collection_check_boxes라는 View 도우미 함수를 사용하여 여러 선택 가능한 확인란을 구현합니다.

app/controllers/recipe_controller.rb
class RecipesController < ApplicationController
def new
    @recipe = Recipe.new
  end

  def create
    @recipe = Recipe.new(recipe_params)
    @recipe.user_id = current_user.id
    @recipe.save!
    redirect_to recipe_path(@recipe)
  end

  private
  def recipe_params
    params.require(:recipe).permit(:recipe_title, :recipe_body, :image, :recipe_food, category_ids: [])
  end
end

category_ids는 체크 박스의 각 체크와 관련된 ID를 포함합니다.

app/views/recipes/index.html.erb
<% @recipes.each do |recipe| %>
・
・
・
  <% recipe.categories.each do |category| %>
    <%= category.category_name %>
  <% end %>
<% end %>

위의 설명에서 처음에 표시한 두 번째 이미지처럼 category_name이 표시됩니다.

마지막으로



이번 다대다의 어소시에이션, collection_check_boxes 메소드에 대한 구현을 했습니다!
collection_check_boxes 메소드에 대해서는 아직 이해가 얕기 때문에 조금 더 깊게 공부합니다.
길어졌지만 여기까지 봐 주셔서 감사합니다! !

참고



htps : // m / sh 012b / ms / 3 a 595f에서 14516081d f5
htps : // 코 m / 카와 z3 / ms / 에 755 아 58177212f2 아카 6c

좋은 웹페이지 즐겨찾기