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

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

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

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

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Q&A

0回答

749閲覧

user_id内に紐づいた投稿のみ表示する方法

KOO_

総合スコア58

Ruby on Rails 5

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

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

0グッド

1クリップ

投稿2019/01/25 04:56

現在プログラミングにて、user_idに紐づいた投稿(@small)のみを表示したくプログラミングを構築しています。

その中で、現在/smalls/newのパスからindexに渡らない現象が発生しております。

また、user_idの設定も初めてなので、もし間違っている点があればご教示頂けないでしょうか?

よろしくお願い致します。

20190124064501_add_user_id_to_smalls.rb class AddUserIdToSmalls < ActiveRecord::Migration[5.2] def change add_column :smalls, :user_id, :integer end end

user

1class User < ApplicationRecord 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :validatable 6 7 has_one :company 8 has_one :small 9 has_one :invoice 10 has_one :carrier 11end 12

small

1class Small < ApplicationRecord 2 belongs_to :company 3 belongs_to :user 4 5 validates :user_id, presence: true 6end

applicationcontroller

1class ApplicationController < ActionController::Base 2before_action :set_current_user, only: [:create] 3 4 def set_current_user 5 @current_user = User.find_by(id: session[:user_id]) 6 end 7 8 def forbid_login_user 9 if @current_user 10 flash[:notice] = "すでにログインしています" 11 redirect_to("/companies/index") 12 end 13 end 14

smallcontroller

1class SmallsController < ApplicationController 2 before_action :authenticate_user!, except: [:top] 3 before_action :forbid_login_user 4 layout 'small' 5 6 def index 7 @smalls = Small.all.order(created_at: 'desc') 8 @company = Company.all 9 end 10 11 def show 12 @small = Small.find_by(id: params[:id]) 13 @user = User.find_by(id: @small.user_id) 14 @company = @small.company 15 end 16 17 def new 18 @small = Small.new 19 end 20 21 def create 22 @small = Small.new(small_params) 23 if @small .save 24 redirect_to smalls_path 25 else 26 render 'new' 27 end 28 end

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

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

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

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

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

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問