Rails 4 - Has_many problems

Asked

Viewed 49 times

0

I need help displaying in the view the value in the view of a relationship with has_many.

I have my product model:

class Product < ActiveRecord::Base
paginates_per 15

has_many :product_images, :dependent => :delete_all

I’m doing a find on this model:

@products = Product.where(:active => 1).includes(:product_images)

But I can’t do it for example

@product.image_products.id

What is wrong? Thank you.

1 answer

0

When Voce uses has_many, it will return an array of objects, that is, if Voce calls only the '.id', it will not allow it, because the '.id' is the attribute of an object, and it will not be able to catch it if you do it in an array...

However, if Voce wants the object ids, which I think is what Voce would need in this case, Voce could use the 'Pluck' method, this method will return for example, all that attribute of all the arrays of that object... would look something like this...

@product.image_products.pluck(:id)

In Rails 4, Voce will only be able to take in this case an attribute for you, already in Rails 5, allows Voce to make a Pluck of 2 attributes of those objects, which makes the function much more interesting...

I hope it helped, thanks!!

  • thanks helped yes was breaking the head, but this solution was quite useful. But even in Rails 5 as you mentioned it is possible to pass 2 attributes I found still a little limited.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.