Forum: Ruby on Rails Help needed with ActiveRecord

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
D682fb52b72608533ffc364cf04e59f9?d=identicon&s=25 RubyNewbie (Guest)
on 2005-12-28 21:34
I am having issues with RoR/database relationships

I have 3 tables

Feeds (List of feeds)
FeedItems (List of items, feedsID)
FeedView (list of views and their list of feedsID)

I would like to be able to generate a view with the feeditems

For example, if the view has 2 feeds --> CNN & MSNBC and they both have
15 feeds in the feeditems table I want to be able to generate a view
with cnn and msnbc and have 5 feeds respectively.

**Little rusty on coding right now and very new to RoR**

Any pointers would be greatly appreaciated!!
97cbca14d17274370cce501bbea7980a?d=identicon&s=25 Mike Harris (Guest)
on 2005-12-28 23:48
(Received via mailing list)
I would have either 4 or 5 tables.

Either (FeedItems) or (FeedItems and Feeds_FeedItems) - Depends on
whether the "items" are simply identifiers or objects that deserve their
own table
FeedViews - only holds info about the view, not what feeds it contains
Feeds_FeedViews - holds what feeds belong to what views

Assuming you wanted the first 5 items from each of the 2 feeds, and you
want no seperation between them, you would have code something like this

class FeedController
  def view_items #invoked by
    @view = FeedView.find(params[:id])
    @items = @view.first_n_from_each_feed(5) #return an array of length

class FeedView
  has_and_belongs_to_many :feeds
  def first_n_from_each_feed(n)
    items =
    feeds.each do |feed|
      items << feed.items[0...n]
    items.flatten # causes method to return an array of 10 items, not an
array of 2 arrays, each with 5 items

For the view, I would create a partial template, named _feeditem.rhtml.
The leading _ means the file is a partial template, as opposed to a
standard template.  That partial template (implicitly) takes a variable
"feeditem" representing the feeditem to be rendered.  The trivial

<%= feeditem.title + "<br>" + feeditem.body %>

the <% %> denote ruby code, and the = tells it to output the result to
the page

In your view_items.rhtml (which the view_items action wants to invoke)
you'd want something like this

<%= render(:partial => "feeditem", :collection => @items ) %>

the partial parameter tells the method to render the partial template
"_feeditem.rhtml" and the collection paramater says to render each
element in the list items.  it's the same as doing this

<% for item in @items %>
  <%= render(:partial => "feeditem", :object => item %>
<% end %>

This topic is locked and can not be replied to.