Show each users each post.
I'm trying to create a page where all my users are listed, and every movie they've added to their account.
My UserController index def
def index
@users = User.all
if logged_in?
@user = User.find(session[:user_id])
@movies = @user.movies
end
end
And my user index.html.haml
#content#users
- @users.each do |user|
%li
= link_to user.name, user
.movie
- @movies.each do |movie|
.movie-frame
= movie.title
= image_tag(movie.image)
At the moment the -@movies.each do
shows all the movies that are added to my database, it does this for every user. And not specifically the movies that that user has in his account. How do I show each movie for each user?
So you'll need a join table between Movies and Users. Something like UserMovie
is a standard naming scheme for that. You could also give them a name like Favorite
.
In essence you'll do this:
class User < ActiveRecord::Base
has_many :user_movies
has_many :movies, through: :user_movies
end
class UserMovie < ActiveRecord::Base
belongs_to :movie
belongs_to :user
end
class Movie < ActiveRecord::Base
has_many :user_movies
has_many :users, through: :user_movies
end
This lets you access @user.movies
to get their movies and you can also get a list of a movie's users (people who favorited it for example) by doing @movie.users
You will need some mechanism to create the join table records, but if you check out the screencast I did on hearts/favoriting/liking, that's pretty much exactly what you'll be doing for that.