Hello fellow developers! Recently I've been playing with Rails 3.0 and after quite a bit of research I'm kinda stuck. I want to know what approach or solution is the best in my case(I couldn't find an answer yet). So what I'm trying to achieve is simple and straight forward.
I want to do something like this:
class User < ActiveRecord::Base
has_many :feeds
has_many :casts, :through => :feeds
end
class Feed < ActiveRecord::Base
has_many :users
has_many :casts
end
class Cast < ActiveRecord::Base
belongs_to :feed
end
So at the end I need to have methods like User.first.feeds to get all the user's feeds and User.first.casts to get all the user's casts through his/her feeds. Also would be nice to have Feed.first.casts and Feed.first.users. Pretty simple, right, but I'm also having a hard time to create migrations for what I'm trying to achieve.
I know that the code above won't work - I've been playing with it so this is just the concept of what I'm trying to achieve.
Basically my questions are: should I do it through join model somehow or use scopes?(also could you give a code snippet) and how do I do migration for that?
Thanks, and sorry I couldn't find much information on the web regarding this simple case.
Edit: has_and_belongs_to_many on User and Feed won't work in my case because it won't allow me to have @user.casts, it gives only @user.feeds and @feed.users
What you want is a many to many relationship between User and Feed.
You'll want something like this in your code for the User and Feed relationship to work.
You can read more about this in the Rails Guides - http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association
You may also want to look at using has_many :through with an intermediate model for this (explained here http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many) if you'd like to store any meta data for a user-feed relationship record.
Edit: I managed to get a similar setup working on 3.0 as well as 3.1 (using has_many :through).
Here are the contents of my models.
and here are the migrations I used
In http://railscasts.com/episodes/265-rails-3-1-overview Ryan Bates says that rails 3.1 has support for chained has_many :through calls. It's not possible in 3.0