The model Teacher has attributes of :name, :period1, :period2, :period3
In a part of the view I am iterating with an “upto” clause and have
made an instance variable named “hold_period” that has a strings like
“period1” , “period2”
I am successfully using things like teacher.send(hold_period) to access
period column data from a given teacher instance.
What I want to do now is search a whole collection of teachers and find
matches to a string like “on break” in the attribute column stored in
hold_period.
Can you not just query the database with the correct where statement? I
cant think of a good reason why you wouldn’t be able to do it…
I was afraid I’d get that sort of answer ! lol
The problem is I don’t know anything about databases except what I’ve
learned by learning what I got so far from rails. I’d prefer to keep the
code in rails rather than database specific queries.
I think I’m finding the answer on page 303 of the AWDwR book find_by_sql
but I’m having a hard time understanding whats going on there (probably
because I’m not quite clear on what “select” and “where” do and even
more unclear of how to limit the search to only the collection at hand
and to use the column named in the variable).
I guess there’s no time like the present to crack open that dusty mysql
in 24 hours book I never really got through. (I’d still appreciate
someone taking a stab at the example I laid out)
@on_break = @teachers.find :all, :conditions => {hold_period =>
“on_break”}
should do the trick (you might have to convert hold_period to a
symbol, can’t remember off the top of my head.
for the record, if you absolute had to do it that way, you can always do
Foo.send(“find_by_#{attribute_name}”, attribute_value)
That said, I don’t think there’s much point. Dynamic finders increase
readibility compared to find :all, :conditions => ‘…’, but once you
start mucking around with send and constructing the method name on the
fly you’ve lost that readability advantage.