Kombo
Kombo

Reputation: 2381

Rails 3 - Loop through to get a collection?

I'm implementing search and am having some difficulties with my sql/finding.

Basically, I have a favorites page, that gets a collection of favorites with:

@favorites = current_user.votes

In the view, I then loop through my favorites, and can call .voteable on them to get the actual object that was voted on. This is making search very difficult for me to write.

I was wondering if it was possible to change my original collection, so that I'm actually getting the .voteable objects each time to dry up my view/help me write my search. I cannot called current_user.votes.voteables but individually can do something like current_user.votes.first.voteable

What I've attempted is a loop like so:

@favorites = current_user.votes.each {|vote| vote.voteable }

Which is wrong, and I'm just getting my votes again, and not the actual voteable object. I was just wondering if there was a way to get these voteables from looping through my votes like this.

Any pointers would help, thanks.

EDIT:

Expansion what I mean by search:

I'm building a method in the model that searches self, here is an example:

def self.search(search)
    if search
      where('title LIKE ?', "%#{search}%")
    else
      scoped
    end
  end 

I pass in search from the view, with a form like:

<div id="search_form">
    <%= form_tag topic_links_path, :method => 'get', :id => "links_search" do %>
      <%= text_field_tag :search, params[:search], :size => "35"  %>
      <%= submit_tag "Search", :name => nil %>
    <% end %>
  </div>  

That way, when I make my collection in the controller, I can call .search(params[:search]) to get only the items that are like whatever the user entered in the form. I'm using the vote_fu gem for handling the votes/voteables.

Upvotes: 1

Views: 1659

Answers (1)

Pan Thomakos
Pan Thomakos

Reputation: 34340

You need to use map instead of each:

@favorites = current_user.votes.map {|vote| vote.voteable }

each simply loops through the elements and performs the operation on them, but it doesn't return the result in an array format. That's what map does.

On a side note, you can use a scope for search instead of a function. It might be a little cleaner:

scope :search, lambda{ |title| where('title LIKE ?', "%#{title}%") unless title.blank? }

Upvotes: 3

Related Questions