E
E
eldar_web2015-08-19 11:48:58
Ruby on Rails
eldar_web, 2015-08-19 11:48:58

How to assign another object to an array of objects in Rails?

There is a model is admissible:
@autos = Auto.all
I want to assign other records to this @autos through a loop in the condition. How to do it?

@autos.each do |auto|
    if(auto.weight < 1000)
       @autos << auto --- так не работает
    end
end

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Kungurov, 2015-08-19
@evgenykungurov

What attributes does @autos(model) have and which would you like to assign? Let's say:
@autos.map { |auto| auto.my_attr = my_example if auto.weight < 1000 }

T
thepry, 2015-08-19
@thepry

arr = []
@autos.each do |auto|
    arr << auto if auto.weight < 1000 
end

@autos += arr

A
Anton Misyagin, 2015-08-21
@sunnmas

maybe you wanted this: @autos = Auto.where("weight < 1000")? It's just that you first select everything in the loop, and then you want to leave only those that satisfy the condition and put it back into the same array. Although this is not usually asked)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question