레일 튜토리얼 (http://guides.rubyonrails.org/getting_started.html)을 통해 기사 모델을 만들었습니다. 내 응용 프로그램에 주석 부분을 추가하지 않았습니다. Devise가 사용자를 처리하도록 설정했습니다.belongs_to : user를 /app/models/article.rb에 추가하면 기사에 게시물을 올릴 수 없습니다.
잘 작동하고 사용자가 서로의 게시물을 만들고, 편집하고, 삭제할 수있었습니다. 이제는 사용자가 자신의 기사 게시물 만 편집하거나 삭제할 수있게하려고합니다.
사용자가 기사를 만들 때 "사용자가 존재해야합니다"오류가 발생합니다. 내가 belongs_to를 추가하는 것으로 나타났습니다 : 사용자가이 오류를 만드는 것입니다. 이 문제를 해결할 수있는 방법이 있습니까?
내가 가진 참조 및 외래 키를 추가 :
rails g migration AddUserToUploads user:references
그때 나는이 마이그레이션 확인했다 :
class AddUserToArticles < ActiveRecord::Migration[5.0]
def change
add_reference :articles, :user, foreign_key: true
end
end
내가 추가 : 응용 프로그램에 'belongs_to 사용자가'/ 모델/article.rb을
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