Rails get related items through two different relationships

I have a "two middleman" model setup as shown below:

User
  has_many :comments
  has_many :ratings

Comment
  belongs_to :user
  belongs_to :movie

Rating
  belongs_to :user
  belongs_to :movie

Movie
  has_many :comments
  has_many :ratings

Whats the best way to get all Movies that a User is associated with (either commented on or rated)?

I'd like to be able to call User.get_movies(user_id) and get back an ActiveRecord::Relation object so that it's chainable (i.e. User.get_movies(user_id).limit(3).order(...)). This returns a regular old array, and I suspect I'm hitting the database way more than I need to be.

def self.get_movies(user_id)
  user = self.where(:id => user_id).includes({:comments => :movie}, {:ratings => :movie})
  movies = []
  user.comments.each do |comment|
    movies.push(comment.movie)
  end
  user.ratings.each do |rating|
    movies.push(rating.movie)
  end
  movies.uniq!
end

Answers


def movies
  Movie.includes(:ratings, :comments).where("`ratings`.user_id = ? OR `comments`.user_id = ?", self.id, self.id)
end

Untested, but I'm pretty sure using a joins instead of includes also works.


Need Your Help

A .Add method that adds user input to an existing list

c# .net visual-studio list methods

I am trying to create an Add method that allows the user to enter a team which will then be added to list<string> teams, it will then display the lists contents. It need to have the following

ASP.net Vb.Net Label.Text not updating

asp.net vb.net label

In my VB.net ASP application, i have some ASPTREEVIEW where, on page load there is a Label, to which i set some value. After clicking on any row, i catch that value & assign it to the label.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.