belongs_to with multiple models
I am a Rails noob and have a q开发者_运维百科uestion. I have a feed aggregator that is organized by this general concept:
Feed Category (books, electronics, etc) Feed Site Section (home page, books page, etc) Feed (the feed itself) Feed Entry
So:
class Category < ActiveRecord::Base
has_many :feeds
has_many :feed_entries, :through => :feeds, :limit => 5
validates_presence_of :name
attr_accessible :name, :id
end
class Section < ActiveRecord::Base
has_many :feeds
has_many :feed_entries, :through => :feeds, :limit => 5
attr_accessible :name, :id
end
class Feed < ActiveRecord::Base
belongs_to :categories
belongs_to :sections
has_many :feed_entries
validates_presence_of :name, :feed_url
attr_accessible :name, :feed_url, :category_id, :section_id
end
class FeedEntry < ActiveRecord::Base
belongs_to :feed
belongs_to :category
belongs_to :section
validates_presence_of :title, :url
end
Make sense? Now, in my index page, I want to basically say... If you are in the Category Books, on the Home Page Section, give me the feed entries grouped by Feed...
In my controller:
def index
@section = Section.find_by_name("Home Page")
@books = Category.find_by_name("Books")
end
In my view:
<%= render :partial => 'feed_list',
:locals => {:feed_group => @books.feeds}
-%>
This partial will spit out the markup for each feed entry in the @books collection of Feeds. Now what I need to do is somehow combine the @books with the @section...
I tried this:
<%= render :partial => 'feed_list',
:locals => {:feed_group => @books.feeds(:section_id => @section.id)}
-%>
But it isn't limiting by the section ID. I've confirmed the section ID by using the same code in the console...
Make sense? Any advice?
Thanks!
Try something like this:
:locals => {:feed_group => @books.feeds.all(:conditions => {:section_id => @section.id})}
精彩评论