質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

3回答

1667閲覧

rails テーブルのidを取得

Meitoku

総合スコア44

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2020/10/09 03:46

編集2020/10/09 12:03

編集(edit,update)画面で、そのツイートに基づくcategory_idを取得する方法が分かりません

tweetテーブル

idnamecategory_id
2Aくん1

ページのurl /tweets/2/edit

categoryテーブル

idname
1

そのツイートに紐づくcategoryテーブルのidを取得したいです

上の例でいうと
ツイートid2に紐づくcategoryテーブルのid1を取得したいです

現在実装しているのが以下ですが、取ってこれていません

@category = Category.find(params[:id])

####追記

######簡単な実装の説明
多階層のカテゴリを実装しています
現在取得したいidというのは親カテゴリのidです
以下で親カテゴリのidを取得して、childrenメソッドで子カテゴリのidを取得できるのかなと思っています

def edit @category_children = Category.find(params[:id]).children end

そしてviewファイルで子カテゴリを全てセレクトボックスで表示させようかと思っています

<%=f.select :school_a_id,options_for_select(@category_children.map{|c| [c[:name], c[:id]]},selected: @tweet.tournament_id),{},{class: "tournament_select_child",id: "children_category"} %>

###各ファイル

tweetモデル

class Tweet < ApplicationRecord validates :title_info,length: {maximum: 30} validates :tournament_id,:school_a,:school_b,:school_a_score,:school_b_score,:text,:title_info ,presence: true mount_uploader :image, ImageUploader belongs_to :user has_many :tournaments has_many :categories has_many :liked_users,through: :likes,source: :user belongs_to :school_a,class_name: 'Category', foreign_key: 'school_a_id' belongs_to :school_b,class_name: 'Category', foreign_key: 'school_b_id' end

categoryモデル

class Category < ApplicationRecord has_many :tweets has_ancestry has_many :school_a_tweets,class_name: 'Tweet', foreign_key: 'school_a_id' has_many :school_b_tweets,class_name: 'Tweet', foreign_key: 'school_b_id' end

tweet.controller.rb

class TweetsController < ApplicationController before_action :search_tweet,only:[:show,:destroy,:edit,:update] before_action :move_to_index,except: :index before_action :set_category, only: [:index,:new, :edit, :create, :update, :destroy] def index @tweets = Tweet.includes(:user).page(params[:page]).per(5).order("created_at DESC") end def new @tweet=Tweet.new respond_to do |format| format.html format.json do @category_children = Category.find(params[:tournament_id]).children end end end def create @tweet=Tweet.create(tweet_params) render "new" unless @tweet.save end def show @nickname=current_user.nickname @comments = @tweet.comments.includes(:user) @like = Like.new end def destroy @tweet.destroy if @tweet.user_id == current_user.id end def edit @category_children = Category.find(params[:id]).children end def update @tweet.update(tweet_params) if @tweet.user_id == current_user.id || current_user.admin redirect_to action: :show end def get_category_children @category_children = Category.find(params[:tournament_id]).children end def search_tweet @tweet = Tweet.find(params[:id]) end def move_to_index redirect_to action: :index unless user_signed_in? end private def set_category @category_parent_array = Category.where(ancestry: nil) end def tweet_params params.require(:tweet).permit(:image,:text,:title_info,:school_a_score,:school_b_score,:school_a_id,:school_b_id,:tournament_id).merge(user_id: current_user.id) end end

edit.html.erb

<div class="contents row"> <%= form_with(model: @tweet,local: true) do |f|%> <%= f.label "大会選択" %> <%=f.select :tournament_id, options_for_select( @category_parent_array.map{|c| [c[:name], c[:id]]},selected: @tweet.tournament_id),{include_blank:"大会を選択してください"}, { class: "parent_category_box", id: "parent_category"}%> <div class="school"></div> <%=f.select :school_a_id,options_for_select(@category_children.map{|c| [c[:name], c[:id]]},selected: @tweet.tournament_id),{},{class: "tournament_select_child",id: "children_category"} %> <div class="school2"></div> <%= render partial: "form",locals: {f: f} %> <% end %> <%= link_to "戻る","/tweets/#{@tweet.id}",class:"back"%> </div>

_form.html.erb

<p>高校A 得点</p> <%= f.select :school_a_score, options_for_select((1..50).to_a,selected: @tweet.school_a_score),{include_blank:"得点を選択してください"} %> <p>高校B 得点</p> <%= f.select :school_b_score, options_for_select((1..50).to_a,@tweet.school_b_score),{include_blank: "得点を選択してください"} %> <%= f.text_field :title_info,placeholder: "タイトル",class: "game_record",value: "#{@tweet.title_info}" %> <%= f.text_area :text, cols: 30 ,rows: 10,value: "#{@tweet.text}" %> <%= f.label :image, class: "form-image" do %> <h4>画像投稿</h4> <i class="fa fa-image"></i> <%= f.file_field :image, class: 'input-box_image_file',value: "#{@tweet.image}"%> <% end %> <%=f.submit value: "SENT",class: "game_record"%>

tweet.js

$(document).on('turbolinks:load', (function(){ function appendOption(category) { let html = `<option value="${category.id}" data-category="${category.id}">${category.name}</option>`; return html; } function appendChildrenBox(insertHTML) { let childSelectHtml = ''; childSelectHtml = `<p>高校A</p> <select name="tweet[school_a_id]" class="tournament_select_child" id="children_category"> <option value="" data-category="" >学校を選択してください</option> ${insertHTML}</select>` $(".school").append(childSelectHtml) childSelectHtml2 = `<p>高校B</p> <select name="tweet[school_b_id]" class="tournament_select_child" id="children_category"> <option value="" data-category="" >学校を選択してください</option> ${insertHTML}</select>` $(".school2").append(childSelectHtml2) } $("#parent_category").on("change",function(){ let parentCategory = $("#parent_category").val(); if(parentCategory !=""){ $.ajax({ type: 'GET', url: '/tweets/new', data: {tournament_id: parentCategory}, dataType: 'json' }) .done(function(children){ $(".school").empty(); $(".school2").empty(); let insertHTML = ''; children.forEach(function(child) { insertHTML += appendOption(child); }); appendChildrenBox(insertHTML); }) .fail(function() { alert('error:子カテゴリーの取得に失敗'); }) } });

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

winterboum

2020/10/09 04:27

params[:id] にはなにのidがはいってますか?
Meitoku

2020/10/09 06:07

nilになっています
winterboum

2020/10/09 06:20

ではcodeを載せていただかないとわからないですね 各modelと 「@category = Category.find(params[:id])」 を実行しているcontrollerと そのcontrollerを呼び出している viewを載せてください
Meitoku

2020/10/09 07:02

追記しました よろしくお願いします
winterboum

2020/10/09 09:14

@category = Category.find(params[:id]) がみあたりませんが
Meitoku

2020/10/09 09:19

editアクションになります 本来は、子カテゴリを取得したいので、childrenメソッドをつけています childrenメソッドを外した状態でnilを確認しました
winterboum

2020/10/09 09:52

このeditアクションはどのviewのどこから呼ばれますか
Meitoku

2020/10/09 10:03

edit.html.erbの6行目です
winterboum

2020/10/09 10:30

<%=f.select :school_a_id, ですか? これはたんなるselectで リクエストを発行するとは思えませんが
Meitoku

2020/10/09 10:44 編集

すみません、リクエスト発行というのがよく分かりませんでして・・・ 6行目で子カテゴリが入った(エラーで入ってませんが)@category_childrenをセレクトボックスにしてるつもりです ここで@category_childrenを呼んでいるのではないでしょうか
winterboum

2020/10/09 11:47

js 使ってません?
Meitoku

2020/10/09 12:05

追記しました 新規投稿の時にjsでカテゴリを選択します 親カテゴリによって子カテゴリが変わる実装です editでは親カテゴリを固定して、jsを使わないようにしようと思います
guest

回答3

0

自己解決

アソシエーションを利用して以下でできました

@category = Category.find_by(name: @tweet.category.name) @category_children = @category.children

投稿2020/10/10 12:26

編集2020/10/10 12:28
Meitoku

総合スコア44

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

ancestryの使い方はそれなりに記事が出ていると思うので、それを参考にどこまでできてて何ができないか具体的に書いたほうが良いと思います

もう少し原因調査と説明を頑張ってみてください

投稿2020/10/09 14:52

kokitail

総合スコア135

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

はて、、、というcodeです

そのJSは親をカテゴリーを変えた時に呼ばれるもので、
しかも new を呼んでます ???

edit を呼んでいるcodeが無いです。

載せているのは エラーが起きた時の状態のcodeですか?
全部を載せていますか?

「必要な」所だけ載せるのは「どこが必要なのか」わかっている場合です。
それがわかるなら自力で解けるでしょうから、解けないなら下手に編集すると解決が遅れます。

投稿2020/10/09 12:53

winterboum

総合スコア23331

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Meitoku

2020/10/09 14:33

はい、これが現在のコードです 今の状態では新規投稿は行えますし、テキストはupdateできる状態なのですが・・
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問