views:

63

answers:

2

I have the following models:

student class teacher

a student can have multiple classes, a class can have 0 or 1 teachers. I want to be able to call a method on the student to see if they have a specific teacher, and return true or false.

The following code seems to work, but i thought it looked a bit long winded, having to compare each of the teachers attributes against those in the DB.

a_teacher = Teacher.new(:name => "Bob", :age => 30)

self.classes.all(:conditions => ["teacher.name = ? AND teacher.age = ?", a_teacher.name,a_teacher.age], :joins => :teacher)

I thought there might be a way to pass a_teacher into the find, instead of specifying the attribute seperatly. Thanks

A: 

I think you have to use it as you wrote in quesiton. ActiveRecord doesn't analyze the query string in this way to guess a instance method of passed object. You should consider to create some named_scope for example: by_teacher(teacher) wich will be search by name and age, if you need it.

Sebastian
A: 

I want to be able to call a method on the student to see if they have a specific teacher, and return true or false.

Why are you looking up the teacher by name and age, as opposed to the teacher ID?

self.classes.all(:conditions => ["teacher_id = ?", teacher_student_is_interested_in.id])

Your question is pretty hard to follow. Post more of your model if you need a more detailed answer.

Edit: Given the extra info you've posted, it sounds like you're attempting something that is more like a search. I would suggest reading up on the following:

  1. named_scope
  2. searchlogic
jdl
I dont have a teacher ID, the user inputs a teacher name, and age, and submits, then i display a specific students name, along with whether the teacher entered is one of the students teachers.
Gungho
You have teachers in your db. Why are you not looking up a specific id from the student's input? What happens when two 30-year-olds named Bob are both teachers?
jdl
I am trying to look up a specific id from the users input, and if i find one, i return true. If the are both called bob, and have the same age as the one entered, i return true.
Gungho
Alright. See my edit above.
jdl