DNorthrup DNorthrup - 6 days ago 5
Ruby Question

Rails 5 - Iterating over part of an array for the view

I currently use EasyAutoComplete for a search form. If you hit 'View All' it redirects to the same page but with params[:name] to show all cards.

I render this with:

<% @cards.in_groups_of(6, false).each do |group| %>
<div class='row'>
<% group.each do |card| %>
<div class='col-sm-2 col-md-2'>
<div class="wrapperImg">
<%= link_to image_tag(card.image_url, class: "img-responsive"), {:controller => "cards", :action => "show", :id => card.id }%>
</div>
</div>
<% end %>
</div>
</div>
<% end %>


However, if you look up a specific set of cards it's going to return a couple hundred (or more) of essentially the same card. I can identify these cards by a parameter(rarity)

I was originally going to try to modify it in the controller, but that is an issue because the 'def index' makes the EasyAutoComplete work

def index
wild_search = "%#{params[:name]}%"
@cards = Card.order(multiverse_id: :desc).limit(30)
# debugger
#@cards = @cards.where("name like :name", name: wild_search).page(params[:page]) if params[:name]
@cards = @cards.where("name like :name OR setName like :name", name: wild_search).page(params[:page]) if params[:name]
end


Is there a way for me to do something like

cards = @cards.where('rarity IS NOT ?', 'Land')
or something similar in the view, then modify my output from
@cards.in_group_of
to
cards.in_group_of
? Or is there a way to use the Controller to do this and use
def search
instead of
def index
?

Welcome any input.

Answer

Like this?

<% @cards.where.not(rarity: "Land").in_groups_of(6, false).each do |group| %>

http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods/WhereChain.html