Christopher Spears
Christopher Spears

Reputation: 1105

Trying to grab ids from foreign keys in Rails 4 (with Mongodb)

I am writing a model in Ruby on Rails using MongoDB with mongoid. I have three models: User, Store, Review. A Review belongs to a User and Store.

class Review
  include Mongoid::Document

  field :rating, type: Float
  field :body, type: String

  belongs_to :user
  belongs_to :store

  def self.is_unique
    where(user: user, store: store).exists?
  end

end

I am trying to find out if a User has already submitted a Review for a Store by looking to see if the Review contains the ids of Store and User. However, I seem to be having trouble grabbing the ids from those foreign keys. From the above code, I get this error message:

undefined local variable or method `user' for Review:Class

Strangely enough, if I add a user field and a store field, I get a similar error.

Upvotes: 0

Views: 78

Answers (1)

PreciousBodilyFluids
PreciousBodilyFluids

Reputation: 12001

With def self.is_unique you're defining a method on the Review class (to be called as Review.is_unique), not on Review instances. I believe what you want is to define def is_unique, so that you could do Review.new(user: user, store: store).is_unique and get a helpful answer.

Upvotes: 1

Related Questions