'name'AR属性返回类名和ID不起作用

时间:2012-03-21 20:04:16

标签: ruby-on-rails ruby-on-rails-3 activerecord

我有一个User对象,得到这样的名字很好:

>u=User.find(1)
>u.name
>jt

但它与一个对象有关联,当我收到用户的时候会返回该类的名称:

oc=ObjectConnection.find(1)
oc.user.name
> User

并且id给了我一个错误:

ruby-1.9.2-p290 :063 > oc.user.id
NoMethodError:   User Load (0.4ms)  SELECT id, name FROM `users` WHERE (id=1)
undefined method `id' for [#<User id: 1, name: "jt">]:ActiveRecord::Relation
    from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0/lib/active_record/relation.rb:459:in `method_missing'
    from (irb):63
    from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands/console.rb:45:in `start'
    from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands/console.rb:8:in `start'
    from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands.rb:40:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'
ruby-1.9.2-p290 :064 >

课程是:

class ObjectConnection < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :object_connections
end

发生了什么事?这看起来很简单。

THX

1 个答案:

答案 0 :(得分:0)

我和Contact和Company之间的关系几乎完全相同(联系belongs_to公司,公司has_many联系人。)这是我的rails控制台(Rails 3.2,Ruby 1.9.3)。

1.9.3p125 :019 > company = Company.find(1)
Company Load (2.7ms)  SELECT "companies".* FROM "companies" WHERE "companies"."id" = $1 LIMIT 1  [["id", 1]]
=> #<Company id: 1, name: "Acme Corp", created_at: "2012-03-20 17:49:44", updated_at: "2012-03-20 17:49:44"> 
1.9.3p125 :020 > contact = Contact.find(1)
Contact Load (1.8ms)  SELECT "contacts".* FROM "contacts" WHERE "contacts"."id" = $1 LIMIT 1  [["id", 1]]
=> #<Contact id: 1, first: "Tom", last: "Harrison", email: "foo@example.com", created_at: "2012-03-12 19:11:57", updated_at: "2012-03-20 17:56:37", birthdate: "1962-02-26", company_id: 1> 
1.9.3p125 :021 > contact.company.name
Company Load (0.7ms)  SELECT "companies".* FROM "companies" WHERE "companies"."id" = 1 LIMIT 1
=> "Acme Corp" 

也许在早期版本的AREL中使用“name”的情况?另外,请注意奇怪的SQL语法... WHERE (id=1) ...如果查找ObjectConnection的其他属性会发生什么?

这是一个相同的情况,不是吗?也许是Rails的版本?红宝石?似乎难以置信,但答案是“你做得对”。