添加 group_id 到笔记

Adding group_id to notes

我正在寻找一个应用程序,其中 user 可以登录,在组中创建 group 和 post notesuser 必须能够邀请其他 user 加入 group(如果他们已经存在),如果他们不存在,请向他们发送注册邀请,并将他们放置在 group

目前有 user groupnotes 模型。我很难将 group_id 添加到 notes 以便 notes 属于该组,并且 group 的索引仅显示 notes group_id

db/migrate

class AddUserIdToNotes < ActiveRecord::Migration
  def change
    add_column :notes, :group_id, :integer
  end
end

models/note.rb

class Note < ActiveRecord::Base
  belongs_to :group
end

models/group.rb

class Group < ActiveRecord::Base
  has_many :notes
end

controllers/notes_controller.rb

class NotesController < ApplicationController
    before_action :find_note, only: [:show, :edit, :update, :destroy]

    def index
        @notes = Note.where(group_id: current_user).order("created_at DESC")
    end

    def new
        @note = current_user.notes.build
    end

    def create
        @note = current_user.notes.build(note_params)

        if @note.save
            redirect_to @note
        else
            render 'new'
        end
    end

    def edit
    end

    def update
        if @note.update(note_params)
            redirect_to @note
        else
            render 'edit'
        end
    end

    def destroy
        @note.destroy
            redirect_to notes_path
    end

    private

    def find_note
        @note = Note.find(params[:id])
    end

    def note_params
        params.require(:note).permit(:title, :content)
    end
end

将 notes_controller.rb 中的代码替换为:

def index @notes = current_user.notes.order("created_at DESC") end

当您将 current_user 传递给 group_id

时,您做错了