jjplack jjplack - 18 days ago 12
Ruby Question

Rails expected, got Array

I'm looking to get a id from a array and when get it shows this on the action add Order.new


Color(#70131258622840) expected, got Array(#70131401174240)


someone have any idea why?

product model

has_many :colorships
has_many :colors, through: :colorships


color model

has_many :colorships
has_many :products, :through => :colorships


product controller

def new
Product.New
@dropdown = @product.colors.collect { |co| [co.name, co.id] }
end

def show
Product.find(params[:id])
color = product.colors.select { |i| [i.id] }
end

def add
product = Product.find(params[:id])
if product
color = product.colors.select { |i| [i.id] }
if order.nil? # create new order
order = Order.new
order.product = product
order.color = color
end
end
end

Answer
color = product.colors.select { |i| [i.id] } 

this line is giving you an array of colors, not a color. This would be more natural

color = product.colors.select { |i| i.id } 

but select gives you an array as well, even of one element in this case. find gives you just the element you want or nil instead

color = product.colors.find { |i| i.id } 
Comments