【问题标题】:Model trouble in rails铁轨中的模型问题
【发布时间】:2012-04-12 20:08:29
【问题描述】:

我有 客户.rb

    class Customer < ActiveRecord::Base
    acts_as_authentic
    has_many :credit_cards
    has_many :telephones
    has_many :virtual_pays
end

电话.rb

    class Telephone < ActiveRecord::Base
    belongs_to :customers
end

当我使用 Rails 控制台广告写入 Customer.all 时,我会从 db 表客户中获取所有数据,但是当我尝试获取包括客户电话在内的所有数据时出现错误 我写:customers.telephones.all,然后我尝试 Customer.Telephone.all,但如何正确执行此操作?

NameError: 未定义的局部变量或方法customers' for main:Object from (irb):6 from /home/pp/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.9/lib/rails/commands/console.rb:44:in start' 来自/home/pp/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.9/lib/rails/commands/console.rb:8:in start' from /home/pp/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.9/lib/rails/commands.rb:23:in ' 来自脚本/rails:6:in require' from script/rails:6:in'

我也更正了写模型?

【问题讨论】:

  • 您想知道如何查询客户电话号码吗?

标签: ruby-on-rails model


【解决方案1】:

在您的电话模型中,它应该是 belongs_to :customer(单数)。

【讨论】:

  • 和console比怎么写?
  • @pavel 你会在你的模型中写,而不是控制台。在您的模型中,您将belongs_to :customers 更改为belongs_to :customer。然后加载控制台并尝试您的客户呼叫。
  • )) 我知道,我问我应该在控制台写什么?客户电话?如果是这样,它不起作用
  • 对不起。从您的评论中不清楚。因为这是一对多的关系(客户有很多电话),我会使用 customers = Customer.all (或者为了简单起见,我会这样做:customer = Customers.first 所以我只是让一个客户回来测试) .然后,在控制台中,您可以执行以下任一操作:customers[0].telephones 或 customer.telephones(取决于您最初在控制台中键入的内容)。希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
  • 2016-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
相关资源
最近更新 更多