has_many
とbelongs_to
の.myコードを追加した後に記事を表示する際に問題があります。追加の関連付け後にエラーになる[Ruby on Rails]
モデル/ blog_post.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_many :blog_posts, inverse_of: :user
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable
mount_uploader :image, ImageUploader
end
モデル/ user.rb
class BlogPost < ApplicationRecord
belongs_to :user, inverse_of: :blog_posts
end
コントローラ/ blog_posts_controller.rb
class BlogPostsController < ApplicationController
before_action :authenticate_user!
def new
@bp = BlogPost.new
end
def create
@bp = BlogPost.new
@bp.user_name = current_user
@bp.title = params[:blog_post][:title]
@bp.content = params[:blog_post][:content]
@bp.save
redirect_to blog_post_path(@bp.id)
end
def show
@bp = BlogPost.find(params[:id])
end
def destroy
@bp = BlogPost.find(params[:id])
@bp.destroy
redirect_to root_path(@bp)
end
end
ビュー/ blog_posts/new.html.slim
h1 Let's post your article!
= form_for @bp do |f|
h2 title
= f.text_field :title
h2 content
= f.text_area :content
br
= f.submit "Submit"
a href="/" Home
ビュー/ blog_posts/show.html.slim
h2 name
p = @user.user_name
h2 title
p = @bp.title
h2 content
p = @bp.content
a href="/"Home
と私はこのエラーを取得... ActionController::UrlGenerationError in BlogPostsController#create``No route matches {:action=>"show", :controller=>"blog_posts", :id=>nil} missing required keys: [:id]
は、この問題を解決するための任意のアイデアはありますか?
迅速な回答ありがとうございました!!それはまだ動作しません... –
私にアドバイスをくれてありがとう!私は私のblog_postsテーブルにuser_idを追加しなかったので、恥ずかしい気がします...その後、それは動作します! –