2017-10-08 8 views
0

레일 튜토리얼 (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 

것은 내가 뭔가를 놓치고를 ? 내 기사에 어떤 변화를 주어야합니까?

+0

사용자가 로그인하지 않고 기사를 만들 수 있습니까? –

+0

아니요, 아직 제한된 사항이 있습니다. Devise가 인증을 처리하고 있습니다. 내가 belongs_to : user를 추가 할 때 문제가 발생한다는 것을 알았습니다. –

+0

'Article'에서 연결을 유지하려고 할 때'Upload'에 참조를 추가했습니다. '기사'에 실제로 user_id 필드가 있습니까? – kiddorails

답변

0

이 같은 컨트롤러의 상단에 여러 before_action의를 가진 시도 할 수 있습니다 :

class ArticlesController < ApplicationController 
    before_action :authenticate_user! 
    before_action :set_post,   only: [:edit, :update, :destroy] 
    before_action :check_post_owner, only: [:edit, :update, :destroy] 

    def edit 
    # just leave this blank - it's fine 
    end 

    def update 
    if @article.update(article_params) 
     redirect_to @article 
    else 
     render 'edit' 
    end 
    end 

    def destroy 
    @article.destroy 
    redirect_to articles_path 
    end 

    private 

    def set_post 
    @article = Article.find(params[:id]) 
    end 

    def check_post_owner 
    if @article.user != current_user 
     flash[:notice] = "You're not the owner" 
     redirect_to articles_path 
    end 
    end 

end 

:authenticate_user!

가 고안 방법입니다. set_postcheck_post_ownerprivate 섹션 내부의 사용자 지정 방법입니다.

@article = Article.find(params[:id]) 줄을 리팩토링 할 수있는 방법을 만들고 before_action 내 전화 번호 set_post 메서드에서 호출 할 수 있습니다. 레일에서

0

당신이 연결 방법

class Article < ApplicationRecord 
    validates :title, presence: true, 
       length: { minimum: 5 } 

    belongs_to :user, required: false 

end 

건배를 통해 자식 레코드를 작성하지 않을 때 자식 레코드를 생성 할 수 있도록 자녀 모델에 필요한 = false를 추가 할 필요가 5!