将group_id添加到备注

时间:2015-04-27 19:46:03

标签: ruby-on-rails ruby devise

我正在构建一个user可以登录的应用程序,在该组中创建group并发布notesuser必须能够邀请其他user加入group,如果它们已经存在,如果它们不存在,请向他们发送注册邀请,并将其放入group 1}}

目前有user groupnotes型号。我在向group_id添加notes时遇到困难,因此notes属于该群组,group的索引仅显示notes group_id {1}}。

分贝/迁移

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

模型/ note.rb

class Note < ActiveRecord::Base
  belongs_to :group
end

模型/ group.rb

class Group < ActiveRecord::Base
  has_many :notes
end

控制器/ 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 个答案:

答案 0 :(得分:0)

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

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

将current_user传递给group_id

时,你做错了