0

i have a Project Model and a ProjectAttribute Model that basically have 3 fields: name, value, project_id, used to store key-value records about Project, i've tried the approach below but without any success.

project.rb

class Project < ActiveRecord::Base
  has_many :project_attributes

  searchable do
    text :title, :boost => 2
    text :description
    string :att_name, :multiple => true do
      project_attributes.map { |p| p.name }
    end

    string :att_value, :multiple => true do
      project_attributes.map { |p| p.value }
    end

  end
end

Its possible to use ProjectAttribute fields as criteria to Project.search getting all projects having 3 rooms?

Ex:

Project.search do 
    with(:att_name, 'rooms')
    with(:att_value, '3')
end
Nando
  • 747
  • 7
  • 23
  • any luck with my answer? – aguynamedloren Mar 27 '13 at 09:03
  • unfortunately not, because i would like to use Sunspot instead of ActiveRecord. your answer is the very same approach that i'm using right now. – Nando Mar 27 '13 at 17:11
  • Can you describe what kind of undesired behaviors you are experiencing? Are you getting errors when executing your search? Are you seeing incorrect results? I'm asking this because the code you've provided looks correct. It would be helpful if you could provide more information as to how you plan on using Sunspot/Solr for types of queries like this. There might other things you can do with Solr (such as using facets) that would be more appropriate. – vanhowen Mar 28 '13 at 20:33

1 Answers1

-2

No need for sunspot - you can do this with basic ActiveRecord queries and scopes.

Let's start simple: you just want to find projects that have 3 rooms. The query would be:

Project.joins(:project_attributes).where("project_attributes.name = 'rooms' AND project_attributes.value = '3'")

turning that into a scope on Project:

scope :search, joins(:project_attributes).where("project_attributes.name = 'rooms' AND project_attributes.value = '3'")

but of course you want to accept variable inputs:

scope :search, lambda { |name, value| joins(:project_attributes).where("project_attributes.name = ? AND project_attributes.value = ?", name, value) }

which allows you to do:

Project.search("rooms","3")
aguynamedloren
  • 2,273
  • 18
  • 23