I followed RailsCasts authentication from scratch (http://railscasts.com/episodes/250-authentication-from-scratch-revised) using the bcrypt-ruby gem and have the best in place gem in the app from another RailsCasts episode (http://railscasts.com/episodes/302-in-place-editing).
I have users, sessions, and tasks models. After the user logs in the application routes the user to tasks#index. Rather than having all tasks display, I want only the tasks that belong to the current_user in tasks#index to display.
My model associations look like this:
Subscription: has_many :users,
Tasks: belongs_to :user,
User: has_many :tasks and belongs_to :subscription
Users table has e-mail and password columns. Tasks table has content column.
The simple authentication from scratch creates a helper method in the application.rb file that I am having difficulty accessing in my tasks controller:
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
My tasks#controller index action looks like..
@tasks = Task.order("position")
@task = Task.new
end`
My tasks#index looks like this:
`
<% @tasks.each do |task| %>
<li id="task_<%= task.id %>"><%= best_in_place task, :content %>
<%= link_to raw("×"), task, method: :delete, remote: true %>
<span class="handle">—</span>
</li>
<% 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 the tasks created by the current user?
Because the User has many Tasks, in your tasks controller you can use the below to restrict the tasks to the current users as per below…