Display tasks related to current_user in index action?

I followed RailsCasts validation from scratch (http://railscasts.com/episodes/250-authentication-from-scratch-revised) using a gem bcrypt-ruby

and has an best in place

in-app gem from another RailsCasts episode (http://railscasts.com / episodes / 302-in-place-editing).

I have user, session and task models. After the user logs into the application, the user's route will be tasks#index

. Instead of displaying all tasks, I want to display only those tasks that are current_user

in the tasks#index


My model associations look like this: Subscription: has_many :users, Tasks: belongs_to :user, User: has_many :tasks and belongs_to :subscription

The users table contains email and password columns. The task table contains a column of content.

Simple authentication from scratch creates a helper method in the application.rb file that I'm having difficulty accessing the task controller with:

def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end helper_method :current_user

My Tasks # the controller index action looks like this.

@tasks = Task.order("position")
@task = Task.new



My # index tasks look like this:

<% @tasks.each do |task| %>
<li id="task_<%= task.id %>"><%= best_in_place task, :content %>
<%= link_to raw("&times;"), task, method: :delete, remote: true  %>
<span class="handle">&mdash;</span>
<% end %>`



<%= form_for(Task.new) do |f| %>
<%= f.text_field  :content, :placeholder => "Add a new task here" %>
<% end %>



How can I restrict tasks to only those created by the current user?


source to share

2 answers

Since the user has many tasks, in the task controller you can use below to restrict tasks to current users as per below ...

@tasks = @current_user.tasks.order("position")
@task = Task.new(:user => @current_user)




Another way is to access the method created in the task model:


def index
     @tasks = current_user_tasks(current_user)


def current_user_tasks(user)
Task.where("tasks.user_id = ?", user.id).order('created_at asc').first


Hope this fixes your problem!



All Articles