Stuart Pontins Stuart Pontins - 7 months ago 20
Ruby Question

How to access todos in another controller rails 4.2?

I'm trying to learn RoR by creating an application, however, I have come across a problem and I'm not sure if my method is flawed or if it's the correct way to do it but I'm going about it slightly wrong. I think it has something to do with the variable being an instance variable and it's not called in my other controller but I'm not sure how to get it there?

Anyway the problem is -

I have a todos controller, models, views etc. set up via the scaffolding in Rails but I want to be able to display the todos to each user in their 'dashboard' so to speak when they log in. Therefore I assume I need the todos to be in the dashboard controller too, right?

Here's my dashboard controller

class DashboardController < ApplicationController
def home
@todos = current_user.todos
end
end


Here I'm calling my todos but they aren't showing when I call them in the view.

and my todos scaffold

class TodosController < ApplicationController
before_action :set_todo, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!

# GET /todos
# GET /todos.json
def index
@todos = current_user.todos
end

# GET /todos/1
# GET /todos/1.json
def show
end

# GET /todos/new
def new
@todo = Todo.new
end

# GET /todos/1/edit
def edit
end

# POST /todos
# POST /todos.json
def create
@todo = current_user.todos.new(todo_params)

respond_to do |format|
if @todo.save
format.html { redirect_to @todo, notice: 'Todo was successfully created.' }
format.json { render :show, status: :created, location: @todo }
else
format.html { render :new }
format.json { render json: @todo.errors, status: :unprocessable_entity }
end
end
end

# PATCH/PUT /todos/1
# PATCH/PUT /todos/1.json
def update
respond_to do |format|
if @todo.update(todo_params)
format.html { redirect_to @todo, notice: 'Todo was successfully updated.' }
format.json { render :show, status: :ok, location: @todo }
else
format.html { render :edit }
format.json { render json: @todo.errors, status: :unprocessable_entity }
end
end
end

# DELETE /todos/1
# DELETE /todos/1.json
def destroy
@todo.destroy
respond_to do |format|
format.html { redirect_to todos_url, notice: 'Todo was successfully destroyed.' }
format.json { head :no_content }
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_todo
@todo = Todo.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def todo_params
params.require(:todo).permit(:title, :item)
end
end


How would I go about displaying my todo items in the dashboard?

Thanks for any help

dkp dkp
Answer

You just need to add

before_action :authenticate_user! 

to DashboardController like the way you have it in TodosController .