I have a User model with a Role attribute, which I defined using enum.
enum role: {'Instructor': 0, 'Student': 1, 'Other': 2}
Now, I have another table Instructor with references from User table.
I have a Course table with references from Instructor.
I want only the Instructor to create a Course not any other role.
I am using Pundit for authorization. I am having problem in creating a new Course.
def create
...
authorize @course
@course.instructor = Instructor.where(user: current_user).first
The above query is rolling back but not saving the course.
Any suggestions would be of greater help.
app/policies/course_policy.rb
class CoursePolicy < ApplicationPolicy
attr_reader :user, :model
def initialize (user, model)
@user = user
@course = model
end
def index?
true
end
def show?
true
end
def create?
@user.Instructor?
end
def update?
@user.Instructor_of? @course
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
scope.all
end
end
end
Rollback Error Output:
ActiveRecord::AssociationTypeMismatch (Instructor(#70064238051700) expected, got #<ActiveRecord::Relation []> which is an instance of Instructor::ActiveRecord_Relation(#70064238083180)):
app/controllers/courses_controller.rb:31:in `create'
Started POST "/courses" for ::1 at 2019-04-13 06:02:33 +0700
Processing by CoursesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"++6oBiY4MeOHZKyMwAJ8VqF9ACayve5e+cmMg7FqG4dbHVCfDpI3uqVK7g75+auf8OABUTEnXlm9jshWu/50EQ==", "course"=>{"name"=>"Ruby on Rails", "description"=>"jk.jlliyf", "start_date(1i)"=>"2019", "start_date(2i)"=>"4", "start_date(3i)"=>"12", "end_date(1i)"=>"2019", "end_date(2i)"=>"7", "end_date(3i)"=>"12"}, "commit"=>"Create Course"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 2], ["LIMIT", 1]]
↳ /home/sagar/.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Instructor Load (1.8ms) SELECT "instructors".* FROM "instructors" WHERE "instructors"."user_id" = $1 ORDER BY "instructors"."id" ASC LIMIT $2 [["user_id", 2], ["LIMIT", 1]]
↳ app/controllers/courses_controller.rb:31
(0.4ms) BEGIN
↳ app/controllers/courses_controller.rb:34
(0.4ms) ROLLBACK
↳ app/controllers/courses_controller.rb:34
Rendering courses/new.html.erb within layouts/application
Rendered courses/_form.html.erb (44.0ms)
Rendered courses/new.html.erb within layouts/application (46.7ms)
Completed 200 OK in 267ms (Views: 124.6ms | ActiveRecord: 32.4ms)
Course Model:
app/models/course.rb
class Course < ApplicationRecord
belongs_to :instructor
end