3

I have a searchlogic that searches for not_null on an association that can occur many times, but I only want to display one UNIQUE/DISTINCT instance of the object:

Company.contact_emails_id_not_null

I only want one Company, no matter how many contact_emails are associated to that Company :through => :contacts

Satchel
  • 16,414
  • 23
  • 106
  • 192

2 Answers2

2

Assuming rails 3:

Company.contact_emails_id_not_null.select("distinct name_of_your_field")

If rails 2.3.x (please forgive me if it turns out to be false I am unsure)

Company.contact_emails_id_not_null.find(:all, :select => "distinct name_of_your_field")

name_of_your_field can also be * to include all fields.

Let me know if that helps.

Hugo
  • 2,913
  • 1
  • 20
  • 21
  • Hi, I'm on rails 2....so I still need to use the find method even with the searchlogic scopes? – Satchel Oct 05 '10 at 03:10
  • doesn't select need the name of a database....I want to show distinct Company names....so which field would I use? – Satchel Oct 05 '10 at 03:11
  • Rails already handles the connection to the database for you. Company (a model) knows which table to return records from. What searchlogic gives you is named scoped to make it easier to get records. Now then, you know what fields are in your Company table ? I can tell you what to use. – Hugo Oct 05 '10 at 13:05
  • hi, it *seems* to work when I use distinct companies.* thanks! gave you the green check! – Satchel Oct 05 '10 at 16:10
  • Yeah was going to propose some such but wasn't sure how your data was modeled. Cheers. – Hugo Oct 05 '10 at 17:20
1

In Rails 2.3.11 this worked for me...

@vendor_search = Vendor.searchlogic
@vendors = @vendor_search.paginate({
                                   :page => page,
                                   :per_page => 32,
                                   :order => 'name',
                                   :select => 'DISTINCT vendors.*'
                               })

There's extra project-specific information in there, but the relevant part is this...

:select => 'DISTINCT vendors.*'
Ethan
  • 57,819
  • 63
  • 187
  • 237