我的RSpec测试不断为我的一个ActiveRecord关联返回NoMethodError

时间:2016-07-29 21:30:44

标签: ruby-on-rails ruby activerecord

我有一个 用户 列表,其架构如下:

  create_table "users", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "name"
  end

  create_table "listings", force: :cascade do |t|
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.string   "name"
    t.string   "address"
    t.string   "listing_type"
    t.string   "title"
    t.string   "description"
    t.integer  "price"
    t.integer  "neighborhood_id"
    t.integer  "host_id"
    t.string   "host"
  end

我的模型列表和用户如下:

class Listing < ActiveRecord::Base
  belongs_to :neighborhood
  belongs_to :hosts, :class_name => "User"
end

class User < ActiveRecord::Base
  has_many :listings, :foreign_key => 'host_id'
end

但是当我运行RSpec测试时,我收到以下NoMethodError:

  1) Listing belongs to a host
     Failure/Error: expect(listing.host.name).to eq("Amanda")
     NoMethodError:
       undefined method `name' for "#<User:0x007fc885001838>":String

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

host表中有listings字符串列 所以listing.host从该列返回一个String。然后你打电话给name 当然没有这样的方法。

我认为你的关联错了。尝试

belongs_to :host, :class_name => "User"

不是hosts

t.string "host"表中删除listings