When referring to DB during each do processing

Asked 1 years ago, Updated 1 years ago, 115 views

I'm a beginner at Ruby.I am trying to reference DB in each do with the following logic:

I try to get the record under where conditions by taking the value of the maxrating variable where the rating is max in the Uear_Rating table and using the id in the books table I reserved before, but the result is only the last record I got.I think it's very basic, but I'm having trouble understanding it, so please tell me how to solve it.

@books.each do|sb|
 maxrating=User_Rating.where(book_id:sb.id).maximum(:rating)
  @search_result=User_Summary.joins('LEFT OUTER JOIN Books ON user_summary.book_id=books.id') .joins('LEFT OUTER JOIN user_rATINGS ON user_summaries.id=user_rATINGs.user_summary_id').where(#="bouchers.sb.id}
end

ruby sinatra

2022-09-30 21:42

1 Answers

(1..10).each do|i|
    @result=i
  end

If you replace it with the code, you will understand what is going on.Only the last i value (=10) is taken out, and every loop between 1 and 9 is overwritten and disappeared with the following i

If you want all the values, for example,

@result=[]
(1..10).each do|i|
  @result<<i#There are other ways to write.
end

and so on.

By the way, looping DB queries is generally a bad practice, and as the number of @books increases, so does the query.

It's a bit complicated, so I think it's hard to rewrite it to just one shot, but remember that you need to rewrite it.

(Or maybe someone will answer)

By the way,

@search_result=User_Summary.joins('LEFT OUTER JOIN BOOKS ON user_summary.book_id=books.id') .joins('LEFT OUTER JOIN user_ratings ON user_sb.id=user_ratings.user_summary_id_users.summaries.id)=" r" _"user_ratsummary_idsummaries. #" {"her"ook"e" )"u"E"er"F"ies" _"d"us" w" _"at" "" i"ar"O" j"user_summary_summary_

In this case, we embed the value in the query string with the variable expansion, but let's not do this.I don't think this example is a problem in terms of type, but if it contains any string, it's a typical security hole.

(Search SQL injection for details)

where(["user_summary.book_id=?", sb.id])

Let's leave it to the library to embed the variables like this.


2022-09-30 21:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.