Joining tables in Rails through relation table
I have three classes; User, Feed, and Entries. Users have one or more Feeds and Feeds have one or more Entries:
class Feed < ActiveRecord::Base
has_many :entries
has_many :feeds_users
has_many :users, :through => :feeds_users, :class_name => "User"
end
Class User < ActiveRecord::Base
has_many :feeds_users
has_many :feeds, :through => :feeds_users, :class_name => "Feed"
end
class Entry < ActiveRecord:Base
belongs_to :feed
end
The User and Feed classes are related through a third table:
class FeedsUser < ActiveRecord::Base
belongs_to :user
belongs_to :feed
end
Now, my problem is that I need to get a certain user's feeds and each feed's latest n entries. I'm fiddling with something like this:
u = User.first
Feed.joins(:entries, :users).where(:entries => { :created_at => (Time.now-2.days)..Time.now }, :users => u)
My problem here is that this generates some SQL that tries to query "users" on t开发者_如何学Pythonhe table "feeds" - which doesn't exist.
How do I go about creating a correct query that can give me all feeds and their latest 10 entries for a given user?
Take out has_many :feeds_users
. :feeds_users
shouldn't be a model.
You should keep the table, but some Rails magic goes on behind the scenes. If you have a table named feeds and a table named users, Rails derives the table name of the look-up unless you specify it differently.
For your example:
Class Feed < ActiveRecord::Base
has_many :users
end
Class User < ActiveRecord::Base
has_many :feeds
end
It will look for the relationship in the users_feeds
table. If it looked like this:
Class Feed < ActiveRecord::Base
belongs_to :user
end
Class User < ActiveRecord::Base
has_many :feeds
end
It would look for the relationship in the user_feeds
table.
It's linguistically correct, as many users will have many feeds in the first example, and one user will have many feeds in the second example. That's also a good indicator of whether your relation logic is correct.
It also sounds like you need the has_and_belongs_to_many
relationship instead of just has_many
.
For a complete run-down on all forms of model associations, check out the guide.
精彩评论