我想使用rails创建一个具有单个rest调用的复杂rest对象实例。 在下面的示例中,当我在带有参数哈希的Person上调用new时,控制器中出现错误。
在看到ActiveSupport :: HashWithIndifferentAccess而不是PhoneNumber时,我收到意外类型的错误
从测试传递的哈希包含一个Hash对象数组,而控制器操作参数创建ActiveSupport :: HashWithIndifferentAccess对象。
即模型:
class Person < ActiveRecord::Base
has_many :phone_numbers , :autosave => true
class PhoneNumber < ActiveRecord::Base
belongs_to :person
person_controller_test.rb
test "should create person" do
newperson=Person.new(:name => "test")
newperson.phone_numbers << PhoneNumber.new(:number => "123-4567")
person_string= newperson.to_xml(:include => :phone_numbers)
person_hash=Hash.from_xml(course_string)
person_hash2=person_hash['person']
post :create, :person => person_hash2, :format => "xml"
assert_response :success
end
person_controller.rb
def create
@person = Person.new(params[:person])
答案 0 :(得分:1)
class Person < ActiveRecord::Base
has_many :phone_numbers , :autosave => true
# this is important for create complex nested object in one call
accepts_nested_attributes_for :phone_numbers
end
class PhoneNumber < ActiveRecord::Base
belongs_to :person
end
person_controller_test.rb
test "should create person" do
newperson=Person.new(:name => "test")
newperson.phone_numbers.build(:number => "123-4567") #more cleaner
# and start from here I'm not sure but this maybe help you
# I think that you must pass a json object
post :create, :person => newperson.to_json(:include => :phone_numbers), :format => "xml"
assert_response :success
end
link:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
答案 1 :(得分:0)
Dinatih,谢谢你的回答!它帮助解决了这个问题。
因为“accepts_nested_attributes_for:phone_numbers”,我遇到了一个小问题, 需要散列键'phone_numbers_attributes'而不是'phone_numbers'的to_xml / to_json序列化默认值。测试代码(下面)看起来有点难看,但它会正确传递并创建对象。不幸的是,将json传递给post方法也不会创建对象。
test "should create complex person" do
newperson=Person.new(:name => "test")
newperson.phone_numbers.build(:number => "123-4567")
person_string= newperson.to_xml(:include => :phone_numbers)
person_hash=Hash.from_xml(person_string)
person_hash2=person_hash['person']
person_hash2[:phone_numbers_attributes] = person_hash2['phone_numbers']
person_hash2.delete('phone_numbers')
p person_hash2
post :create, :person => person_hash2, :format => "xml"
p response.body
assert_select "person" do
assert_select "name", {:text=>"test"}
assert_select "phone-numbers" do
assert_select "phone-number" do
assert_select "number", {:text=>"123-4567"}
end
end
end
assert_response :success
end
答案 2 :(得分:0)
你也应该看看:
和