Rails 4 - Problems with has_many

0

I need help to display 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 not do for example

@product.image_products.id

What's wrong? Thank you.

    
asked by anonymous 22.04.2017 / 00:34

1 answer

0

When you use has_many, it will return an array of objects, that is, if you just call '.id', it will not allow, since '.id' is the attribute of an object, and it does not will be able to get it if you do it in an array ...

However, if you want the ids of the objects, which I think is what you would need in this case, you could use the pluck method, this method will return, for example, all that attribute of all arrays of that object. .. would look more or less like this ...

@product.image_products.pluck(:id)

In rails 4, you will only be able to get an attribute in this case, already in rails 5, allow you to make a pluck of 2 attributes of those objects, which makes the function much more interesting ...

I hope it helped, thanks!

    
23.04.2017 / 23:04