Since we narrowed down multiple conditions using the where method, we will summarize them.
I want to get one piece of information about the developer model created just before the time when the product model was created.
Create a Product model and a Developer. The two models are not associated. (Dare here) The Developer model has information about what product it made (developed_product_number). The product has a product number, and these two values are equal. (If so, let's associate it, but this time we will use this condition.) I want to get the value of the developer created just before the product is created from multiple developers who created the same product.
Let's put the actual code first.
product = Product.find(params[:id])
@Developer = Developer.where(developed_product_number: product.id).where('created_at < ?', product).order(created_at: :desc).limit(1)
It is like this. I will explain
product = Product.find(params[:id])
Get the ID of the target product and assign it to the variable product. Here, enter the value that was narrowed down by adding conditions to the variable @Developer.
@Developer = Developer.where(developed_product_number: product.id).where('created_at < ?', product).order(created_at: :desc).limit(1)
Partially divide.
@Developer = Developer.where(developed_product_number: product.number)
Here, the id of the variable product obtained earlier is obtained.
Then narrow down the values.
where('created_at < ?', product).order(created_at: :desc).limit(1)
Here, we acquired the information of multiple developers created before the time when the product was created, and acquired the information of the first developer counting from the descending order. It's been quite long, so the code here needs to be separated into scopes and so on.
Recommended Posts