Original Question
My app deals with "Machines". Machines have specifications, written as many "Specs". Each of those Specs contains a reference to "Spec_Field" (Fields such as "Weight", "Height", "Capacity", etc), and a value.
Class Machine
has_many :specs
has_many :spec_fields, :through => :specs
Class Spec
belongs_to :machine
belongs_to :spec_field
What I want to do is to have a Search function in the #show action for each Machine, where a user checks off the Specs that he wants to match ("Yes, length 50 is what I need, and capacity 500 is perfect, I don't care for width"), and clicks "Find Similar", which would then find all Machines with similar Specs.
I assume I'll need a model for Search, similar to the following screencast: http://railscasts.com/episodes/111-advanced-search-form-revised?autoplay=true
In the #show action for a Machine, I will then need to go through this Machine's Specs, and add them to the "Search" instance. So does that mean a "Spec" also needs to belong to "Search"?
I just can't wrap my mind around how to organize everything in my case. Any help is appreciated!
Database Schema
Machines:
t.string "title"
t.text "description"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "status"
t.integer "category_id"
t.string "manufacturer"
t.string "model"
t.string "serial"
t.string "year"
t.string "location"
Specs:
t.integer "machine_id"
t.integer "field_id"
t.text "value"
t.float "base_value"
t.integer "unit_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
Spec Fields:
t.string "label"
t.integer "base_units"
Solution That Seems to Work
I added a "With Spec" scope that uses SQL "IN" with "SELECT"
def self.with_spec(field_id,value)
min_value = value.to_f * 0.8
max_value = value.to_f * 1.2
where("machines.id IN (SELECT machine_id FROM specs WHERE field_id = ? AND value > ? AND value < ?)",field_id,min_value,max_value)
end