ruby-on-rails - Rails 关联访问

标签 ruby-on-rails ruby

我希望我能更好地描述这一点,但这是我所知道的最好的方法。我有两个类(class)汽车和颜色。每个人都可以通过关联类 CarColors 拥有许多彼此。协会设置正确我对此很肯定,但我似乎无法让它发挥作用:

@carlist = Cars.includes(:Colors).all

@carlist.colors

错误

@carlist[0].colors

有效

我的问题是如何在不像成功示例中那样声明索引的情况下遍历@carlist?以下是我尝试过但也失败的一些方法:

@carlist.each do |c|
c.colors
end

@carlist.each_with_index do |c,i|
c[i].colors
end

最佳答案

你的第一个例子失败了,因为 Car.includes(:colors).all 返回了一组汽车,而不是一辆车,所以下面的例子会失败,因为 #colors 没有为数组定义

@cars = Car.includes(:colors).all
@cars.colors #=> NoMethodError, color is not defined for Array

以下将起作用,因为迭代器将有一个 car 实例

@cars.each do |car|
  puts car.colors # => Will print an array of color objects
end

each_with_index 也可以,但有点不同,因为第一个对象 和each loop car对象一样,第二个对象是index

@cars.each_with_index do |car, index|
  puts car.colors # => Will print an array of color objects
  puts @cars[index].colors # => Will print an array of color objects
  puts car == @cars[index] # => will print true
end

关于ruby-on-rails - Rails 关联访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11954637/

相关文章:

ruby - 直接在类声明中的if语句

ruby-on-rails - 尝试循环遍历哈希中的项目并仅返回某些项目

ruby-on-rails - 从集合 ActiveRecord 对象中获取特定列?

ruby-on-rails - rails : How to buffer an ActiveRecord query?

ruby-on-rails - rails : Moving a helper method form a test to test_helper. rb

ruby - 您如何模块化 Chef Recipe ?

ruby - 在 OSX Catalina 上安装用于 gem 安装的 Ruby 开发工具

mysql - Rails 无法连接到 mysql2 中的数据库

ruby-on-rails - 将乘客 5.0.23 native 支持与 Ruby 2.2.4 链接失败

ruby-on-rails - load 与 Ruby 中的 require 有何不同?