Daniel
Daniel

Reputation: 3030

ruby hash with database

I am trying to understand this line of code:

@rating = Rating.where(review_id: @review.id, user_id: @current_user.id).first

The line of code comes from a Ruby on Rails app that has a user, review, and rating model. Here is what I understand so far:

How does review_id: @review.id or user_id: @current_user.id work with the database?

Update question: Sorry I'm still confused. How does @review.id or @current_user.id point to anything in the database? I have nothing in my database starting with the @ symbol

Upvotes: 0

Views: 805

Answers (5)

Cybercarnage シ
Cybercarnage シ

Reputation: 525

You have 2 fields: "review_id", "user_id" in table "ratings".

Symbol @ - means that is instance variable and it is available not only in the controller

variable structure example:

@current_user = {
  id: 1,
  name: "Jhon",
  last_name: "Wayne"
}

this means that @current_user.id = 1

user_id: @current_user.id

And query search 1 in table ratings field user_id

Upvotes: 1

Zero Fiber
Zero Fiber

Reputation: 4465

This line selects all the ratings which belong to a review with id @review.id and belong to the currently logged-in user with id @current_user.id.

The SQL version of this will look something like this:

query = "SELECT * FROM ratings WHERE review_id = #{@review.id} AND user_id = #{@current_user.id}"

EDIT: In the hash, every key refers to the column name in the table and the corresponding value is what you are searching for in that column. That value is given by what is stored in the instance variable.

Upvotes: 0

Ahmad Hussain
Ahmad Hussain

Reputation: 2491

When you provide a hash in where clause it means then key of hash is field name and value of that key is value in database

Upvotes: 0

Danil Speransky
Danil Speransky

Reputation: 30453

Rating.where provides ActiveRecord::Relation object, which knows about conditions on review_id and user_id. When you call first for the object -- it executes sql query, and appends LIMIT 1 condition.

SELECT ratings.* FROM ratings WHERE ratings.review_id = 11 AND ratings.user_id = 12 LIMIT 1

The ORM converts the response from the database to the ruby object. Which you place in the instance variable @rating, probably in a controller. This variable will be accessible in the view.

Upvotes: 0

Rahul Singh
Rahul Singh

Reputation: 3427

If you know database SQL queries then

Rating.where(review_id: @review.id, user_id: @current_user.id)

is equivalent to

SELECT * from ratings where review_id = @review.id AND user_id = @current_user.id;
  1. @rating is not just a variable , its a instance variable
  2. Rating.where() will return an array of ratings. and Rating.where().first will return first record of the array

Upvotes: 0

Related Questions