我在添加has_many
和belongs_to
時遇到問題,我的代碼就是這樣。添加關聯後會變成錯誤[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 ......之後,它就起作用了! –