Rails ActiveResource HABTM返回值

时间:2009-03-25 21:36:31

标签: ruby-on-rails activeresource

我有两种模式:公司和用户,他们有一个has_and_belongs_to_many关系。

我正在使用活动资源和方法来获取公司的所有用户:

def users
  @company = Company.find( params[:id], :include => [:users] )
  render :xml => @company.users.to_xml(:include =>[:companies])   
end

唯一的问题是,另一方面,当我调用lookup_users方法时,返回的val是一个数组Company对象,每个对象都有一个company属性而不是User对象数组,每个对象都有一个company属性。输出如下:

有没有人知道如何使用activeresource显式设置返回的对象类型?

这很奇怪,因为在我的服务中调用@ company.users.to_xml会呈现看似正常的xml:注意“<users type='array'>”,但是当它返回时,它就是公司对象。

"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<users type=\"array\">\n  <user>\n    <

上述服务调用的返回值: (rdb:1)pp用户

[#<AsClient::Company:0x1959628   @attributes=    {"work_phone"=>nil,
    "city"=>nil,
    "fax_number"=>nil,
    "company"=>nil,
    "updated_at"=>Wed Mar 25 21:05:43 UTC 2009,
    "postal_code"=>nil,
    "title"=>nil,
    "the_parent_record_id"=>"650",
    "hashed_password"=>"d80052727e9719113277bcc712d647aedefaff4b",
    "last_logged_into"=>nil,
    "last_seen_at"=>nil,
    "customers"=>
     [#<AsClient::Company:0x19568c4
       @attributes=
        {"name"=>"hmvc0joq",
         "updated_at"=>Wed Mar 25 21:05:43 UTC 2009,
         "main_contact"=>nil,
         "id"=>650,
         "customer_id"=>"650",
         "deleted"=>nil,
         "deleted_by"=>nil,
         "user_id"=>"3263",
         "created_at"=>Wed Mar 25 21:05:43 UTC 2009,
         "active"=>nil},
       @prefix_options={}>],
    "created_by"=>"AsTesting",
    "password_salt"=>"m8j35JAnpd0IlllSHDCfd0BE5R1UHoT1",
    "country"=>nil,
    "activation_code"=>"8xB2J7LL3tQuK2Z9I1AKhAcotaSp8zgz",
    "id"=>3263,
    "updated_by"=>nil,
    "password_reset_code"=>nil,
    "address_1"=>nil,
    "home_phone"=>nil,
    "deleted"=>false,
    "address_2"=>nil,
    "deleted_by"=>nil,
    "first_name"=>"Joe",
    "last_name"=>"Test",
    "province"=>nil,
    "mobile_phone"=>nil,
    "suffix"=>nil,
    "alt_email"=>nil,
    "created_at"=>Wed Mar 25 21:05:43 UTC 2009,
    "email"=>"auf@b.c",
    "active"=>false,
    "middle_name"=>nil},   @prefix_options={}>]

2 个答案:

答案 0 :(得分:0)

我真的不明白你的问题是什么。在您的示例中,@ company是object,但@ company.users是用户对象的数组。

致电时:

@company.users.to_xml(:include =>[:companies]) 

这可能会呈现一系列用户,并且每个用户都会包含一系列公司。

答案 1 :(得分:0)

哎呀,我肯定发现了我的问题。我的客户正在打电话

users = Company.find(:all, :params => {:id => company_id}, :from => :users)

这显然会返回公司对象...

我需要更多的睡眠