Reputation: 1749
Arg, I'm a RoR newbie, feeling my way, and every possible reasonable combination I've tried here has failed - pointers very much appreciated:
So I have items and statuses. An item has a status, referenced by status_id:
class Status < ActiveRecord::Base
has_many :items
end
Class Item < ActiveRecord::Base
belongs_to :status
end
A status can be something like "For Sale", "Deleted", "Hidden", "Sold" etc.
On the front page of my website, I have been displaying the last 30 items added in random order:
<% latest_items = Items.last(30).shuffle %>
<% latest_items.each do |i| %>
:
<% end %>
However I only want items displayed where the status of the item is set to display on the front page (eg only display items where the status is For Sale or Sold, but not Hidden).
I may want to add future statuses for items, so I have updated the statuses table to include a column front_page, which is set to either 1 or 0, depending on whether it is to display on the front_page or not. Multiple statuses can be displayed on the front page.
I'm struggling to work out how to reference this status.front_page field, and to build the limited array of Items. I've tried numerous things, and nothing is working. Am I barking up the wrong tree entirely?
If it's of any relevance I'm using Ruby 1.9.2p320 / Rails 3.1.0.rc8
Upvotes: 1
Views: 529
Reputation: 4097
Try using a where
(conditions) statement
Item.joins(:status).where(:statuses => {:name => ["For Sale", "Sold"]}).last(30)
you could also put this into a scope
Class Item < ActiveRecord::Base
scope :homepage_display, joins(:status).where(:statuses => {:name => ["For Sale", "Sold"]}).last(30)
# Then in your view
Item.homepage_display
I would also suggest switching around your associations, Items should not belong_to
status
Upvotes: 2