Accessing another model's attributes

Hi :slight_smile:

I’m new to Rails. I’m trying to make an app where students can login in
and signup for the exam. I have a problem filtering data, where a
student can only see exams which belong to her/his year and department.

Subject has the following columns:
t.string “name”
t.integer “ects”
t.integer “year”
t.integer “professor_id” (foreign key which relates it to
professor).

Its relationship with exam:
has_one :exam

Exam has the following columns:
t.date “start_date”
t.string “department”
t.integer “professor_id”
t.integer “subject_id”

Its relationship with exam:
belongs_to :subject

User has attributes year (year of study) and department. The problem is
that exam only has depatment, but it doesn’t have year.

I have made this in exam.rb

scope :department, -> (department) { where(‘department == ?’,
department) }
scope :year, -> (year) { where(‘subject.year == ?’, year) }

Then I called these methods in exams controller (index action) and
passed the data:

@exams = Exam.department(current_user.department) &&
Exam.year(current_user.year)

There is a problem with a scope year, it doesn’t recognize subject. When
I try to access the list of exams it says this:
SQLite3::SQLException: no such column: subject.year: SELECT “exams”.*
FROM “exams” WHERE (subject.year == 2)

But when I include subject_id: scope :year, -> (year) {
where(‘Subject.find(:subject_id).year == ?’, year) }
It says there is a syntax error: SQLite3::SQLException: near “(”: syntax
error: SELECT “exams”.* FROM “exams” WHERE
(Subject.find(:subject_id).year == 2).

I have tried accessing subject attributes by using delegate and
to_params, but it didn’t help. I’ve been googling this issue for more
than 10 days, but I haven’t been able to find a solution.

I appreciate any kind of help. Thanks in advance :slight_smile:

It’s a lot of work, but it will definitely work once you get through the bugs: use gem Devise for the login and don’t hardcode it and use the gem Petergate for the authorizations on top of Devise. The tricky thing is that you might need to specify things in Devise, but it doesn’t scaffold with an explicit controller file, but if you reach that point somebody will know how to jump in for that little fix for like a $25 freelancer job and then you can continue with Petergate.