检查值是否在结果中(Rails)

时间:2016-06-14 06:51:45

标签: ruby-on-rails ruby ruby-on-rails-4

我有以下型号:

模型/ 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

模型/ movie.rb

class Movie < ActiveRecord::Base
  has_many :ratings, :dependent => :destroy
  has_many :comments, :dependent => :destroy
  belongs_to :channel
  belongs_to :order_movies

模型/ order_movies.rb

class OrderMovie < ActiveRecord::Base
  belongs_to :user
  belongs_to :movie
end

现在我想检查用户是否订购了电影。找出这是真的最直接的方法是什么?有没有办法在不使用if语句的情况下返回true或false?

坦克

2 个答案:

答案 0 :(得分:1)

我相信如果您可以与has_many through:user建立movie关联,则可以查看属于用户的电影数量(用户已订购)或数量用户属于电影(用户已租用该电影)

class User < ActiveRecord::Base
  has_many :order_movies
  has_many :movies, through: :order_movies
end

模型/ movie.rb

class Movie < ActiveRecord::Base
  has_many :order_movies
  has_many :user, through: :order_movies
end

模型/ order_movies.rb

class OrderMovie < ActiveRecord::Base
  belongs_to :user
  belongs_to :movie
end

现在如果你做了

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.
  

更新

您可以通过查看OrderMovie模型来完成此操作。

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

答案 1 :(得分:0)

specific_user = User.find(user_id)
specific_movie = Movie.find(movie_id)
specific_user == specific_movie.user # return true if user rented that movie.