Rails 预期,得到数组
Rails expected, got Array
我想从一个数组中获取一个 id,当获取它时会在操作中显示这个 add Order.new
Color(#70131258622840) expected, got Array(#70131401174240)
有人知道为什么吗?
产品型号
has_many :colorships
has_many :colors, through: :colorships
颜色模型
has_many :colorships
has_many :products, :through => :colorships
产品控制器
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
color = product.colors.select { |i| [i.id] }
此行为您提供了一组颜色,而不是一种颜色。这样会更自然
color = product.colors.select { |i| i.id }
但 select
也给你一个数组,在这种情况下甚至是一个元素。 find
只为您提供您想要的元素或 nil
而不是
color = product.colors.find { |i| i.id }
如您所说,您需要 ID 数组。你也可以通过 product.colors.ids
.
这将 return 颜色 ID 数组。
我想从一个数组中获取一个 id,当获取它时会在操作中显示这个 add Order.new
Color(#70131258622840) expected, got Array(#70131401174240)
有人知道为什么吗?
产品型号
has_many :colorships
has_many :colors, through: :colorships
颜色模型
has_many :colorships
has_many :products, :through => :colorships
产品控制器
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
color = product.colors.select { |i| [i.id] }
此行为您提供了一组颜色,而不是一种颜色。这样会更自然
color = product.colors.select { |i| i.id }
但 select
也给你一个数组,在这种情况下甚至是一个元素。 find
只为您提供您想要的元素或 nil
而不是
color = product.colors.find { |i| i.id }
如您所说,您需要 ID 数组。你也可以通过 product.colors.ids
.
这将 return 颜色 ID 数组。