Reputation: 5619
I've got the following models:
models/user.rb
class User < ActiveRecord::Base
has_many :comment
has_and_belongs_to_many :knowledgeprovider
has_and_belongs_to_many :channel
has_many :order_movie
models/movie.rb
class Movie < ActiveRecord::Base
has_many :ratings, :dependent => :destroy
has_many :comments, :dependent => :destroy
belongs_to :channel
belongs_to :order_movies
models/order_movies.rb
class OrderMovie < ActiveRecord::Base
belongs_to :user
belongs_to :movie
end
Now I want to check if a user has ordered a movie. What is the esiest way to find out if that is true? Is there a way to return true or false without using a if statement?
Tanks at all
Upvotes: 0
Views: 73
Reputation: 3126
I believe if you can do a has_many through:
association with user
and movie
you can check the number of movies that belong to a user(the user has ordered), or the number of users belong to a movie(users have rented that movie)
class User < ActiveRecord::Base
has_many :order_movies
has_many :movies, through: :order_movies
end
models/movie.rb
class Movie < ActiveRecord::Base
has_many :order_movies
has_many :user, through: :order_movies
end
models/order_movies.rb
class OrderMovie < ActiveRecord::Base
belongs_to :user
belongs_to :movie
end
So now if you do
user = User.find(<some_id>)
user.movies #will give you all the movies belonging to that user, (the user has rented)
movie = Movie.find(<some_id>)
movie.users #will give you all the users who have rented this particular movie.
Update
You can do that by checking the OrderMovie model.
if OrderMovie.where(user_id: xx, movie_id: yy).present?
#user has rented the particular movie
else
#user has not rented, as we didn't find a record
end
Upvotes: 1
Reputation: 5895
specific_user = User.find(user_id)
specific_movie = Movie.find(movie_id)
specific_user == specific_movie.user # return true if user rented that movie.
Upvotes: 0