2017-09-10 9 views
0

私はRailsでかなり基本的なアプリケーションを構築しています。主なコントローラは2つあり、ユーザとコメントを使っています。私はBcryptを使用していて、ユーザーの暗号化にsecure_passwordを使用し、ネストしたリソースを使用して、ユーザーがhas_manyのコメントとコメントを所有するようにします。User_idはセカンダリコントローラに渡されません

新しいコメントを保存しようとすると、次のようなエラーメッセージが表示されます。コメントに「user_id」という不明な属性があります。コメント・コントローラーで定義されているCURRENT_USERを使用して行われるべきであるがUSER_IDは、コントローラに渡されていないようだ - 現在、次のようになります。

def new 
    @user = current_user 
    @comment = Comment.new 
    @comment.save 
end 

def create 
    @user = current_user 
    @comment = @user.comments.new(comment_params) 
    @comment.save 
    redirect_to user_comments_path, notice: "Thank you for your comment!" 
end 

......

private 
def comment_params 
    params.require(:comment).permit(:user_id, :location, :title, :body) 
end 

私はログインしているコメントを保存しようとすると、なぜuser_idがコントローラに渡されないのかわかりません。私は非常にいくつかのアドバイスをありがとう、ありがとう。

答えて

0

私は新しいコメントを保存しようと、私はエラーメッセージは、次の です。コメントのために「不明な属性 『のuser_id』

belongs_to関連アソシエーションを使用して、あなたが実際に持っています外部キーを格納するテーブルに列を追加

あなたがして、マイグレーションを生成できます。

rails g migration add_user_id_to_comments user:belongs_to 

次に、rails db:migrateで移行してください。

あなたのコントローラは、同様に、多くの問題があります。

def new 
    @comment = current_user.comments.new 
    # never save in new method! 
end 

def create 
    @comment = current_user.comments.new(comment_params) 
    # you always have to check if save/update was successful 
    if comment.save 
    redirect_to user_comments_path, notice: "Thank you for your comment!" 
    else 
    render :new 
    end 
end 

あなたがそれをmemoizingべきであるとして、別のインスタンス変数にcurrent_userを保存する必要はありません。

def current_user 
    @current_user ||= session[:user_id] ? User.find(session[:user_id]) : nil 
end 
関連する問題