Ruby on Rails Monday, February 13, 2017



On Sunday, February 12, 2017 at 11:29:26 AM UTC, Aida Delic wrote:

 

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. 


Delegate,to_params etc. are all rails things, that your database server (or in this case sqlite) doesn't understand. You need to do a join between the two tables, which will result in columns from both tables being available. Rails can help you write those joins (since you have told it about your relationships), but you should understand what those joins are. For example you can do

Exam.joins(:subject).where(subjects: {year: 2}) 

Note that the joins clause use :subject (the name of the association) whereas the where clause uses subjects (the name of the table). You can also supply a raw fragment of sql for the join if you want a different one to what rails generates by default (a left join in this case).

Fred

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/23d87b8c-ce66-4d4a-82a9-4ee412a16a3a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment