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!!
on 2005-12-28 21:34
on 2005-12-28 23:48
I would have either 4 or 5 tables. Feeds 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 yoursite.com/feed/view_items/1 @view = FeedView.find(params[:id]) @items = @view.first_n_from_each_feed(5) #return an array of length 10 end end class FeedView has_and_belongs_to_many :feeds def first_n_from_each_feed(n) items = Array.new feeds.each do |feed| items << feed.items[0...n] end items.flatten # causes method to return an array of 10 items, not an array of 2 arrays, each with 5 items end end 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 example: <%= 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 %> Helpful?