私はRailsチュートリアル(http://guides.rubyonrails.org/getting_started.html)を通って記事モデルを作成しました。アプリケーションにコメント部分を追加しませんでした。私はユーザを扱うDeviseを設定しました。belongs_to:userを/app/models/article.rbに追加すると記事に投稿できません
これはうまくいき、ユーザーは他の投稿を作成、編集、破棄することができました。私は今、ユーザーが自分の記事投稿を編集または削除できるようにしたいと考えています。
私はいくつかの変更を加えましたが、ユーザーが記事投稿を作成しようとすると、「ユーザーが存在する必要があります」というエラーが表示されます。私はbelongs_toを追加することに気付きました。ユーザーはこのエラーを作成しています。これを修正する方法はありますか?
私は、参照して外部キーを追加しました:私は "belongs_toのを:ユーザの追加
class AddUserToArticles < ActiveRecord::Migration[5.0]
def change
add_reference :articles, :user, foreign_key: true
end
end
:アプリ/モデル/ article.rbに私はその後、私はこれを移行したことを確認しました
rails g migration AddUserToUploads user:references
class Article < ApplicationRecord
validates :title, presence: true,
length: { minimum: 5 }
belongs_to :user
end
マイアプリ/モデル/ user.rb次のようになります:それは次のように見える
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :lockable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :articles
end
私の意見では、ユーザーの制限が一時的に無効になっています。
マイarticles_controller.rbは、このように設定されている:私はこれに破壊する方法を変更しようとしたが、それはまだ何もしません
class ArticlesController < ApplicationController
def index
@articles = Article.all
if params[:search]
@articles = Article.search(params[:search]).order("created_at DESC")
else
@articles = Article.all.order('created_at DESC')
end
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text, :description, :keyword, :syntax, :programlang)
end
:
def destroy
@article = Article.find(params[:id])
if user_signed_in? && current_user.articles.exists?(@article.id)
@article.destroy
else
redirect_to articles_path
end
end
私は何かが足りません?私の記事にどのような変更を加える必要がありますか?
ユーザーはログインしていない記事を作成できますか? –
いいえ、私はまだ物事が制限されています。 Deviseは認証を処理しています。私は、belongs_to:userを追加したときに問題が発生することを知りました。 –
'Article'で関連付けを維持しようとしているときに' Upload'に参照を追加しました。あなたの '記事'は実際にuser_idフィールドを持っていますか? – kiddorails