Adding group_id to notes

2019-08-17 07:50发布

问题:

I'm looking to build an application where a user can sign in, create a group and post notes in the group. user must be able to invite other user to the group if they already exist, and if they don't exist send them an invitation to sign up, and place them in that group

Currently there is a user group and notes model. I am having difficulties adding a group_id to the notes so that notes belong to the group, and the index for the group only shows notes what that 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

回答1:

Replace your code in the notes_controller.rb with:

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

You're doing it wrong when you pass the current_user to the group_id