In my application I want only current user to edit and delete his/her
stuff
and for others stuff he just able to show it. I’m using devise with
rails 4.
Here my files.
Migration
rails g migration AddUserIdToStudents user:references
user.rb
class User < ActiveRecord::Base
has_many :students
end
student.rb
class Student < ActiveRecord::Base
belongs_to :user
end
student_controller.rb
class StudentsController < ApplicationController
before_action :authenticate_user!
before_action :set_student, only: [:show, :edit, :update, :destroy]
def index
end
Branch wise students
def mechanical
@students = Student.where(Branch: “Mechanical Engineering”)
end
def infomation_technology
@students = Student.where(Branch: “Information Technology”)
end
def new
@student = current_user.students.build
end
def edit
end
def create
@student = current_user.students.build(student_params)
respond_to do |format|
if @student.save
format.html { redirect_to @student}
format.json { render :show, status: :created, location: @student
}
else
format.html { render :new }
format.json { render json: @student.errors, status:
:unprocessable_entity }
end
end
end
private
def set_student
@student = Student.find(params[:id])
end
def student_params
params.require(:student).permit( :University_Roll_Number, :avatar,
:Department_Type, :user_id)
end
end
_actions.html.erb
<% @students.each do |student| %>
<div class="center-align">
<!-- If Statement -->
<% if current_user.try(:admin?) %>
<%= link_to student, :class=> "btn waves-light waves-effect grey
darken-4" do %>
<span class="button-name">Show</span>
<% end %>
<%= link_to edit_student_path(student), :class=> "btn
waves-light
waves-effect grey darken-4" do %>
<span class="button-name">Edit</span>
<% end %>
<%= link_to student, method: :delete, data: { confirm: 'Are you
sure?’ }, :class=> “btn waves-light waves-effect grey darken-4” do %>
<span class="button-name">Delete</span>
<% end %>
<!-- Else If Statement -->
<% elsif @student.user_id == current_user.id %>
<%= link_to student, :class=> "btn waves-light waves-effect grey
darken-4" do %>
<span class="button-name">Show</span>
<% end %>
<%= link_to edit_student_path(student), :class=> "btn
waves-light
waves-effect grey darken-4" do %>
<span class="button-name">Edit</span>
<% end %>
<%= link_to student, method: :delete, data: { confirm: 'Are you
sure?’ }, :class=> “btn waves-light waves-effect grey darken-4” do %>
<span class="button-name">Delete</span>
<% end %>
<!-- Else Statement -->
<% else %>
<%= link_to student, :class=> "btn waves-light waves-effect grey
darken-4" do %>
<span class="button-name">Show</span>
<% end %>
<% end %>
</div>
With all that configuration I’m getting following error undefined
method
`user_id’ for nil:NilClass. In my students table user_id is passing but
still facing this error. Where am I doing wrong.
–
Cheers!
Deepak Kumar Sharma
Guru Nanak Dev Engineering College
India!