0

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:

  • @rating is a variable
  • Rating.where().first is a method
  • review_id: @review.id + user_id: @current_user.id are parameters- and are an implicit hash key/value pair

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

5 Answers 5

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.