Reputation: 683
I'm trying to loop over my 'offers' collection in a partial, but each 'offer' has a column 'featured' which is a boolean which defaults to false. I'm trying to loop over the collection and only display the offers which have the featured column set to true.
I currently have:
<%= render @offers %>
Trying below but comes back with 'undefined method 'featured'
<%= render @offers if @offer.featured == true %>
Any help would be fantastic
Upvotes: 3
Views: 377
Reputation: 76774
To correct your immediate code, you're calling .featured
on @offer
- which doesn't exist.
You'll either need to loop through @offers
and use logic on offer
, or use conditions inside the partial (which is highly inefficient):
<% @offers.each do |offer| %>
<%= render offer if offer.featured %>
<% end %>
or
<%= render @offers %>
#_offer.html.erb
<% if offer.featured %>
This is super inefficient
<% end %>
--
@jason
is correct with his recommendation of using a where
clause
You may even want to go a step further and set up a scope:
#app/models/offer.rb
class Offer < ActiveRecord::Base
scope :featured, -> { where featured: true }
end
@offers = Offer.featured
You can even chain the scope:
@offers = Offer.where(user_id: params[:id])
<%= render @offers.featured %>
Upvotes: 1
Reputation: 2743
In your controller, set up another collection:
@featured_offers = Offer.where(featured: true)
And render that instead:
<%= render @featured_offers %>
Upvotes: 4