Rails3无法使用has_one DSL创建嵌套模型

时间:2013-01-04 11:17:39

标签: ruby-on-rails ruby-on-rails-3.2

我使用Rails3.2.8做一些练习,这是我的模型:

class Incident < ActiveRecord::Base
  attr_accessible :category, :user, :status, :reference, :location
  belongs_to :user
  has_one :location
  accepts_nested_attributes_for :location

  validates_presence_of :location, :user, :category


end

class Location < ActiveRecord::Base
  attr_accessible :latitude, :longitude, :street
  belongs_to :incident
end

这是我的测试:

require 'spec_helper'

describe Incident do
  before (:each) do
    @user = create(:user, :name => "user1")
    @incident_data = {:category => "House Break in", :user => @user,
                      :location => {:latitude => "-28.1940509", :longitude => "28.0359692",
                                    :street => "abc name"}}
  end
  describe "After create Incident successfully" do
    it "should create location" do
      incident = Incident.create(@incident_data)

      expect(incident.location.latitude).to eq("-28.1940509")
    end
  end
end

我想要做的是在创建Incident对象时自动创建Location对象。但测试失败的原因如下:

失败/错误:事件= Incident.new(@incident_data)

的ActiveRecord :: AssociationTypeMismatch:

预计位置(#70156311891820),得到哈希(#70156307112200)

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

明确指出该位置应该是Location的实例,而不是Hash

:location => {:latitude => "-28.1940509", :longitude => "28.0359692",
                                :street => "abc name"}

但是,一旦您使用嵌套属性,它应该是location_attributes(请参阅NestedAttributes docs):

:location_attributes => {:latitude => "-28.1940509", :longitude => "28.0359692",
                                :street => "abc name"}

或者您可以创建Location对象

:location => Location.new(:latitude => "-28.1940509", :longitude => "28.0359692",
                                :street => "abc name")