vendredi 5 août 2016

Rails 3.2 boolean function in model

I have a Person model (ActiveRecord::Base) with a many-to-many relationship with a tags table/model. When I enter p = Person.find(1), then p.tags in the console, I get the tags I'd expect. All good.

I just added a boolean function to my Person model:

def is_rogue_dentist?
  tags.detect { |t| t.name == "Rogue Dentists" }.present?
end

When I run this against a Person that isn't tagged "Rogue Dentist", I get false as I'd expect. So far so good.

However, if I run it against a Person who does have a "Rogue Dentist" tag, it also returns false.

Curious, I went to the console and found a Person with the "Rogue Dentist" tag (p = Person.find(733)), then ran p.tags.detect { |t| t.name == "Rogue Dentists" }.present? --- identical code to what's inside the boolean function. That returned true.

It doesn't help that I'm relatively new to Rails and have run into a lot of underground functionality that's tripped me up. But I'm totally baffled. Any suggestions?

Aucun commentaire:

Enregistrer un commentaire